ko-fx/src/main/java/org/apidesign/html/kofx/LoadJSON.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 03 May 2013 10:27:06 +0200
changeset 60 939453361b2d
parent 54 0cc18086f731
child 73 f7e7223e94d4
permissions -rw-r--r--
A way to parse an input stream and create a JSON object
jaroslav@37
     1
/**
jaroslav@37
     2
 * HTML via Java(tm) Language Bindings
jaroslav@37
     3
 * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
jaroslav@37
     4
 *
jaroslav@37
     5
 * This program is free software: you can redistribute it and/or modify
jaroslav@37
     6
 * it under the terms of the GNU General Public License as published by
jaroslav@37
     7
 * the Free Software Foundation, version 2 of the License.
jaroslav@37
     8
 *
jaroslav@37
     9
 * This program is distributed in the hope that it will be useful,
jaroslav@37
    10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
jaroslav@37
    11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
jaroslav@37
    12
 * GNU General Public License for more details. apidesign.org
jaroslav@37
    13
 * designates this particular file as subject to the
jaroslav@37
    14
 * "Classpath" exception as provided by apidesign.org
jaroslav@37
    15
 * in the License file that accompanied this code.
jaroslav@37
    16
 *
jaroslav@37
    17
 * You should have received a copy of the GNU General Public License
jaroslav@37
    18
 * along with this program. Look for COPYING file in the top folder.
jaroslav@37
    19
 * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
jaroslav@37
    20
 */
jaroslav@37
    21
package org.apidesign.html.kofx;
jaroslav@37
    22
jaroslav@37
    23
import java.io.IOException;
jaroslav@60
    24
import java.io.InputStream;
jaroslav@37
    25
import java.io.InputStreamReader;
jaroslav@37
    26
import java.io.PushbackInputStream;
jaroslav@37
    27
import java.io.Reader;
jaroslav@37
    28
import java.net.MalformedURLException;
jaroslav@37
    29
import java.net.URL;
jaroslav@37
    30
import java.util.Iterator;
jaroslav@37
    31
import java.util.concurrent.Executor;
jaroslav@37
    32
import java.util.concurrent.Executors;
jaroslav@37
    33
import java.util.logging.Level;
jaroslav@37
    34
import java.util.logging.Logger;
jaroslav@37
    35
import javafx.application.Platform;
jaroslav@37
    36
import javafx.scene.web.WebEngine;
jaroslav@37
    37
import netscape.javascript.JSObject;
jaroslav@37
    38
import org.apidesign.html.json.spi.JSONCall;
jaroslav@37
    39
import org.json.JSONArray;
jaroslav@37
    40
import org.json.JSONException;
jaroslav@37
    41
import org.json.JSONObject;
jaroslav@37
    42
import org.json.JSONTokener;
jaroslav@60
    43
import org.openide.util.Exceptions;
jaroslav@37
    44
jaroslav@54
    45
/** This is an implementation package - just
jaroslav@54
    46
 * include its JAR on classpath and use official {@link Context} API
jaroslav@54
    47
 * to access the functionality.
jaroslav@37
    48
 *
jaroslav@37
    49
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jaroslav@37
    50
 */
jaroslav@37
    51
final class LoadJSON implements Runnable {
jaroslav@37
    52
    private static final Logger LOG = FXContext.LOG;
jaroslav@37
    53
    private static final Executor REQ = Executors.newCachedThreadPool();
jaroslav@37
    54
jaroslav@37
    55
    private final JSONCall call;
jaroslav@37
    56
    private final URL base;
jaroslav@37
    57
    private Throwable error;
jaroslav@37
    58
    private Object json;
jaroslav@37
    59
jaroslav@37
    60
jaroslav@37
    61
    private LoadJSON(JSONCall call) {
jaroslav@37
    62
        this.call = call;
jaroslav@37
    63
        URL b;
jaroslav@37
    64
        try {
jaroslav@37
    65
            b = new URL(findBaseURL());
jaroslav@37
    66
        } catch (MalformedURLException ex) {
jaroslav@37
    67
            LOG.log(Level.SEVERE, "Can't find base url for " + call.composeURL("dummy"), ex);
jaroslav@37
    68
            b = null;
jaroslav@37
    69
        }
jaroslav@37
    70
        this.base = b;
jaroslav@37
    71
    }
jaroslav@37
    72
jaroslav@37
    73
    public static void loadJSON(JSONCall call) {
jaroslav@37
    74
        REQ.execute(new LoadJSON((call)));
jaroslav@37
    75
    }
jaroslav@37
    76
jaroslav@37
    77
    @Override
jaroslav@37
    78
    public void run() {
jaroslav@37
    79
        if (Platform.isFxApplicationThread()) {
jaroslav@37
    80
            if (error != null) {
jaroslav@37
    81
                call.notifyError(error);
jaroslav@37
    82
            } else {
jaroslav@37
    83
                call.notifySuccess(json);
jaroslav@37
    84
            }
jaroslav@37
    85
            return;
jaroslav@37
    86
        }
jaroslav@37
    87
        final String url;
jaroslav@37
    88
        if (call.isJSONP()) {
jaroslav@37
    89
            url = call.composeURL("dummy");
jaroslav@37
    90
        } else {
jaroslav@37
    91
            url = call.composeURL(null);
jaroslav@37
    92
        }
jaroslav@37
    93
        try {
jaroslav@37
    94
            final URL u = new URL(base, url.replace(" ", "%20"));
jaroslav@37
    95
            final PushbackInputStream is = new PushbackInputStream(u.openStream(), 1);
jaroslav@37
    96
            boolean array = false;
jaroslav@37
    97
            if (call.isJSONP()) {
jaroslav@37
    98
                for (;;) {
jaroslav@37
    99
                    int ch = is.read();
jaroslav@37
   100
                    if (ch == -1) {
jaroslav@37
   101
                        break;
jaroslav@37
   102
                    }
jaroslav@37
   103
                    if (ch == '[') {
jaroslav@37
   104
                        is.unread(ch);
jaroslav@37
   105
                        array = true;
jaroslav@37
   106
                        break;
jaroslav@37
   107
                    }
jaroslav@37
   108
                    if (ch == '{') {
jaroslav@37
   109
                        is.unread(ch);
jaroslav@37
   110
                        break;
jaroslav@37
   111
                    }
jaroslav@37
   112
                }
jaroslav@37
   113
            } else {
jaroslav@37
   114
                int ch = is.read();
jaroslav@37
   115
                array = ch == '[';
jaroslav@37
   116
                is.unread(ch);
jaroslav@37
   117
            }
jaroslav@37
   118
            Reader r = new InputStreamReader(is, "UTF-8");
jaroslav@37
   119
jaroslav@37
   120
            JSONTokener tok = new JSONTokener(r);
jaroslav@37
   121
            Object obj = array ? new JSONArray(tok) : new JSONObject(tok);
jaroslav@37
   122
            json = convertToArray(obj);
jaroslav@37
   123
        } catch (JSONException | IOException ex) {
jaroslav@37
   124
            error = ex;
jaroslav@37
   125
            LOG.log(Level.WARNING, "Cannot connect to " + url, ex);
jaroslav@37
   126
        } finally {
jaroslav@37
   127
            Platform.runLater(this);
jaroslav@37
   128
        }
jaroslav@37
   129
    }
jaroslav@37
   130
jaroslav@37
   131
    private static Object convertToArray(Object o) throws JSONException {
jaroslav@37
   132
        if (o instanceof JSONArray) {
jaroslav@37
   133
            JSONArray ja = (JSONArray)o;
jaroslav@37
   134
            Object[] arr = new Object[ja.length()];
jaroslav@37
   135
            for (int i = 0; i < arr.length; i++) {
jaroslav@37
   136
                arr[i] = convertToArray(ja.get(i));
jaroslav@37
   137
            }
jaroslav@37
   138
            return arr;
jaroslav@37
   139
        } else if (o instanceof JSONObject) {
jaroslav@37
   140
            JSONObject obj = (JSONObject)o;
jaroslav@37
   141
            Iterator it = obj.keys();
jaroslav@37
   142
            while (it.hasNext()) {
jaroslav@37
   143
                String key = (String)it.next();
jaroslav@37
   144
                obj.put(key, convertToArray(obj.get(key)));
jaroslav@37
   145
            }
jaroslav@37
   146
            return obj;
jaroslav@37
   147
        } else {
jaroslav@37
   148
            return o;
jaroslav@37
   149
        }
jaroslav@37
   150
    }
jaroslav@37
   151
    
jaroslav@37
   152
    public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
jaroslav@37
   153
        if (jsonObject instanceof JSONObject) {
jaroslav@37
   154
            JSONObject obj = (JSONObject)jsonObject;
jaroslav@37
   155
            for (int i = 0; i < props.length; i++) {
jaroslav@37
   156
                try {
jaroslav@37
   157
                    values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
jaroslav@37
   158
                } catch (JSONException ex) {
jaroslav@37
   159
                    LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
jaroslav@37
   160
                }
jaroslav@37
   161
            }
jaroslav@37
   162
        }
jaroslav@37
   163
        if (jsonObject instanceof JSObject) {
jaroslav@37
   164
            JSObject obj = (JSObject)jsonObject;
jaroslav@37
   165
            for (int i = 0; i < props.length; i++) {
jaroslav@37
   166
                Object val = obj.getMember(props[i]);
jaroslav@37
   167
                values[i] = isDefined(val) ? val : null;
jaroslav@37
   168
            }
jaroslav@37
   169
        }
jaroslav@37
   170
    }
jaroslav@37
   171
    
jaroslav@60
   172
    public static Object parse(InputStream is) throws IOException {
jaroslav@60
   173
        try {
jaroslav@60
   174
            InputStreamReader r = new InputStreamReader(is, "UTF-8");
jaroslav@60
   175
            JSONTokener t = new JSONTokener(r);
jaroslav@60
   176
            return new JSONObject(t);
jaroslav@60
   177
        } catch (JSONException ex) {
jaroslav@60
   178
            throw new IOException(ex);
jaroslav@60
   179
        }
jaroslav@60
   180
    }
jaroslav@60
   181
    
jaroslav@37
   182
    private static String findBaseURL() {
jaroslav@37
   183
        WebEngine eng = (WebEngine) System.getProperties().get("webEngine");
jaroslav@37
   184
        return (String) eng.executeScript(
jaroslav@37
   185
            "var h;"
jaroslav@37
   186
            + "if (!!window && !!window.location && !!window.location.href)\n"
jaroslav@37
   187
            + "  h = window.location.href;\n"
jaroslav@37
   188
            + "else "
jaroslav@37
   189
            + "  h = null;"
jaroslav@37
   190
            + "h\n");
jaroslav@37
   191
    }
jaroslav@37
   192
jaroslav@37
   193
    private static boolean isDefined(Object val) {
jaroslav@37
   194
        return !"undefined".equals(val);
jaroslav@37
   195
    }
jaroslav@37
   196
}