ko-ws-tyrus/src/main/java/org/netbeans/html/wstyrus/LoadJSON.java
author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
Thu, 09 Jan 2014 20:39:23 +0100
branchUniversalKO
changeset 446 6dce58c06f58
parent 442 ko4j/src/main/java/org/netbeans/html/ko4j/LoadJSON.java@bd85dbbdc60c
child 525 d1537ad194c2
permissions -rw-r--r--
ko4j registers implementation of Transfer and WSTransfer based on XHR and WebSocket from a browser. The Java implementations of these interfaces has been moved to ko-ws-tyrus module. JavaScript arrays passed as parameters to Java callback methods need to be wrapped.
jaroslav@37
     1
/**
jaroslav@358
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jaroslav@37
     3
 *
jaroslav@365
     4
 * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
jaroslav@37
     5
 *
jaroslav@358
     6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
jaroslav@358
     7
 * Other names may be trademarks of their respective owners.
jaroslav@37
     8
 *
jaroslav@358
     9
 * The contents of this file are subject to the terms of either the GNU
jaroslav@358
    10
 * General Public License Version 2 only ("GPL") or the Common
jaroslav@358
    11
 * Development and Distribution License("CDDL") (collectively, the
jaroslav@358
    12
 * "License"). You may not use this file except in compliance with the
jaroslav@358
    13
 * License. You can obtain a copy of the License at
jaroslav@358
    14
 * http://www.netbeans.org/cddl-gplv2.html
jaroslav@358
    15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
jaroslav@358
    16
 * specific language governing permissions and limitations under the
jaroslav@358
    17
 * License.  When distributing the software, include this License Header
jaroslav@358
    18
 * Notice in each file and include the License file at
jaroslav@358
    19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
jaroslav@358
    20
 * particular file as subject to the "Classpath" exception as provided
jaroslav@358
    21
 * by Oracle in the GPL Version 2 section of the License file that
jaroslav@358
    22
 * accompanied this code. If applicable, add the following below the
jaroslav@358
    23
 * License Header, with the fields enclosed by brackets [] replaced by
jaroslav@358
    24
 * your own identifying information:
jaroslav@358
    25
 * "Portions Copyrighted [year] [name of copyright owner]"
jaroslav@358
    26
 *
jaroslav@358
    27
 * Contributor(s):
jaroslav@358
    28
 *
jaroslav@358
    29
 * The Original Software is NetBeans. The Initial Developer of the Original
jaroslav@358
    30
 * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
jaroslav@358
    31
 *
jaroslav@358
    32
 * If you wish your version of this file to be governed by only the CDDL
jaroslav@358
    33
 * or only the GPL Version 2, indicate your decision by adding
jaroslav@358
    34
 * "[Contributor] elects to include this software in this distribution
jaroslav@358
    35
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
jaroslav@358
    36
 * single choice of license, a recipient has the option to distribute
jaroslav@358
    37
 * your version of this file under either the CDDL, the GPL Version 2 or
jaroslav@358
    38
 * to extend the choice of license to its licensees as provided above.
jaroslav@358
    39
 * However, if you add GPL Version 2 code and therefore, elected the GPL
jaroslav@358
    40
 * Version 2 license, then the option applies only if the new code is
jaroslav@358
    41
 * made subject to such option by the copyright holder.
jaroslav@37
    42
 */
jaroslav@446
    43
package org.netbeans.html.wstyrus;
jaroslav@37
    44
jaroslav@37
    45
import java.io.IOException;
jaroslav@60
    46
import java.io.InputStream;
jaroslav@37
    47
import java.io.InputStreamReader;
jaroslav@75
    48
import java.io.OutputStream;
jaroslav@37
    49
import java.io.PushbackInputStream;
jaroslav@37
    50
import java.io.Reader;
jaroslav@74
    51
import java.net.HttpURLConnection;
jaroslav@37
    52
import java.net.MalformedURLException;
jaroslav@37
    53
import java.net.URL;
jaroslav@74
    54
import java.net.URLConnection;
jaroslav@37
    55
import java.util.Iterator;
jaroslav@37
    56
import java.util.concurrent.Executor;
jaroslav@37
    57
import java.util.concurrent.Executors;
jaroslav@158
    58
import java.util.concurrent.ThreadFactory;
jaroslav@37
    59
import java.util.logging.Level;
jaroslav@37
    60
import java.util.logging.Logger;
jaroslav@131
    61
import net.java.html.js.JavaScriptBody;
jaroslav@37
    62
import org.apidesign.html.json.spi.JSONCall;
jaroslav@37
    63
import org.json.JSONArray;
jaroslav@37
    64
import org.json.JSONException;
jaroslav@37
    65
import org.json.JSONObject;
jaroslav@37
    66
import org.json.JSONTokener;
jaroslav@37
    67
jaroslav@54
    68
/** This is an implementation package - just
jaroslav@54
    69
 * include its JAR on classpath and use official {@link Context} API
jaroslav@54
    70
 * to access the functionality.
jaroslav@37
    71
 *
jaroslav@37
    72
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jaroslav@37
    73
 */
jaroslav@37
    74
final class LoadJSON implements Runnable {
jaroslav@446
    75
    private static final Logger LOG = Logger.getLogger(LoadJSON.class.getName());
jaroslav@158
    76
    private static final Executor REQ = Executors.newCachedThreadPool(new ThreadFactory() {
jaroslav@158
    77
        @Override
jaroslav@158
    78
        public Thread newThread(Runnable runnable) {
jaroslav@158
    79
            Thread thread = Executors.defaultThreadFactory().newThread(runnable);
jaroslav@158
    80
            thread.setDaemon(true);
jaroslav@158
    81
            return thread;
jaroslav@158
    82
        }
jaroslav@158
    83
    });
jaroslav@37
    84
jaroslav@37
    85
    private final JSONCall call;
jaroslav@37
    86
    private final URL base;
jaroslav@37
    87
jaroslav@37
    88
jaroslav@37
    89
    private LoadJSON(JSONCall call) {
jaroslav@37
    90
        this.call = call;
jaroslav@446
    91
        this.base = null;
jaroslav@37
    92
    }
jaroslav@37
    93
jaroslav@37
    94
    public static void loadJSON(JSONCall call) {
jaroslav@258
    95
        assert !"WebSocket".equals(call.getMethod());
jaroslav@258
    96
        REQ.execute(new LoadJSON((call)));
jaroslav@37
    97
    }
jaroslav@37
    98
jaroslav@37
    99
    @Override
jaroslav@37
   100
    public void run() {
jaroslav@37
   101
        final String url;
jaroslav@446
   102
        Throwable error = null;
jaroslav@446
   103
        Object json = null;
jaroslav@446
   104
        
jaroslav@37
   105
        if (call.isJSONP()) {
jaroslav@37
   106
            url = call.composeURL("dummy");
jaroslav@37
   107
        } else {
jaroslav@37
   108
            url = call.composeURL(null);
jaroslav@37
   109
        }
jaroslav@37
   110
        try {
jaroslav@37
   111
            final URL u = new URL(base, url.replace(" ", "%20"));
jaroslav@74
   112
            URLConnection conn = u.openConnection();
jaroslav@74
   113
            if (conn instanceof HttpURLConnection) {
jaroslav@74
   114
                HttpURLConnection huc = (HttpURLConnection) conn;
jaroslav@74
   115
                if (call.getMethod() != null) {
jaroslav@74
   116
                    huc.setRequestMethod(call.getMethod());
jaroslav@74
   117
                }
jaroslav@75
   118
                if (call.isDoOutput()) {
jaroslav@75
   119
                    huc.setDoOutput(true);
jaroslav@75
   120
                    final OutputStream os = huc.getOutputStream();
jaroslav@75
   121
                    call.writeData(os);
jaroslav@75
   122
                    os.flush();
jaroslav@75
   123
                }
jaroslav@74
   124
            }
jaroslav@74
   125
            final PushbackInputStream is = new PushbackInputStream(
jaroslav@74
   126
                conn.getInputStream(), 1
jaroslav@74
   127
            );
jaroslav@37
   128
            boolean array = false;
jaroslav@73
   129
            boolean string = false;
jaroslav@37
   130
            if (call.isJSONP()) {
jaroslav@37
   131
                for (;;) {
jaroslav@37
   132
                    int ch = is.read();
jaroslav@37
   133
                    if (ch == -1) {
jaroslav@37
   134
                        break;
jaroslav@37
   135
                    }
jaroslav@37
   136
                    if (ch == '[') {
jaroslav@37
   137
                        is.unread(ch);
jaroslav@37
   138
                        array = true;
jaroslav@37
   139
                        break;
jaroslav@37
   140
                    }
jaroslav@37
   141
                    if (ch == '{') {
jaroslav@37
   142
                        is.unread(ch);
jaroslav@37
   143
                        break;
jaroslav@37
   144
                    }
jaroslav@37
   145
                }
jaroslav@37
   146
            } else {
jaroslav@37
   147
                int ch = is.read();
jaroslav@138
   148
                if (ch == -1) {
jaroslav@73
   149
                    string = true;
jaroslav@138
   150
                } else {
jaroslav@138
   151
                    array = ch == '[';
jaroslav@138
   152
                    is.unread(ch);
jaroslav@138
   153
                    if (!array && ch != '{') {
jaroslav@138
   154
                        string = true;
jaroslav@138
   155
                    }
jaroslav@73
   156
                }
jaroslav@37
   157
            }
jaroslav@73
   158
            try {
jaroslav@73
   159
                if (string) {
jaroslav@73
   160
                    throw new JSONException("");
jaroslav@73
   161
                }
jaroslav@73
   162
                Reader r = new InputStreamReader(is, "UTF-8");
jaroslav@37
   163
jaroslav@73
   164
                JSONTokener tok = new JSONTokener(r);
jaroslav@73
   165
                Object obj;
jaroslav@73
   166
                obj = array ? new JSONArray(tok) : new JSONObject(tok);
jaroslav@73
   167
                json = convertToArray(obj);
jaroslav@73
   168
            } catch (JSONException ex) {
jaroslav@73
   169
                Reader r = new InputStreamReader(is, "UTF-8");
jaroslav@73
   170
                StringBuilder sb = new StringBuilder();
jaroslav@73
   171
                for (;;) {
jaroslav@73
   172
                    int ch = r.read();
jaroslav@73
   173
                    if (ch == -1) {
jaroslav@73
   174
                        break;
jaroslav@73
   175
                    }
jaroslav@73
   176
                    sb.append((char)ch);
jaroslav@73
   177
                }
jaroslav@73
   178
                json = sb.toString();
jaroslav@73
   179
            }
jaroslav@73
   180
        } catch (IOException ex) {
jaroslav@37
   181
            error = ex;
jaroslav@37
   182
        } finally {
jaroslav@446
   183
            if (error != null) {
jaroslav@446
   184
                call.notifyError(error);
jaroslav@446
   185
            } else {
jaroslav@446
   186
                call.notifySuccess(json);
jaroslav@446
   187
            }
jaroslav@37
   188
        }
jaroslav@37
   189
    }
jaroslav@37
   190
jaroslav@247
   191
    static Object convertToArray(Object o) throws JSONException {
jaroslav@37
   192
        if (o instanceof JSONArray) {
jaroslav@37
   193
            JSONArray ja = (JSONArray)o;
jaroslav@37
   194
            Object[] arr = new Object[ja.length()];
jaroslav@37
   195
            for (int i = 0; i < arr.length; i++) {
jaroslav@37
   196
                arr[i] = convertToArray(ja.get(i));
jaroslav@37
   197
            }
jaroslav@37
   198
            return arr;
jaroslav@37
   199
        } else if (o instanceof JSONObject) {
jaroslav@37
   200
            JSONObject obj = (JSONObject)o;
jaroslav@37
   201
            Iterator it = obj.keys();
jaroslav@37
   202
            while (it.hasNext()) {
jaroslav@37
   203
                String key = (String)it.next();
jaroslav@37
   204
                obj.put(key, convertToArray(obj.get(key)));
jaroslav@37
   205
            }
jaroslav@37
   206
            return obj;
jaroslav@37
   207
        } else {
jaroslav@37
   208
            return o;
jaroslav@37
   209
        }
jaroslav@37
   210
    }
jaroslav@37
   211
    
jaroslav@37
   212
    public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
jaroslav@37
   213
        if (jsonObject instanceof JSONObject) {
jaroslav@37
   214
            JSONObject obj = (JSONObject)jsonObject;
jaroslav@37
   215
            for (int i = 0; i < props.length; i++) {
jaroslav@37
   216
                try {
jaroslav@37
   217
                    values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
jaroslav@37
   218
                } catch (JSONException ex) {
jaroslav@37
   219
                    LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
jaroslav@37
   220
                }
jaroslav@37
   221
            }
jaroslav@446
   222
            return;
jaroslav@37
   223
        }
jaroslav@446
   224
        for (int i = 0; i < props.length; i++) {
jaroslav@446
   225
            values[i] = getProperty(jsonObject, props[i]);
jaroslav@37
   226
        }
jaroslav@37
   227
    }
jaroslav@37
   228
    
jaroslav@446
   229
    @JavaScriptBody(args = {"object", "property"},
jaroslav@446
   230
            body
jaroslav@446
   231
            = "if (property === null) return object;\n"
jaroslav@446
   232
            + "if (object === null) return null;\n"
jaroslav@446
   233
            + "var p = object[property]; return p ? p : null;"
jaroslav@446
   234
    )
jaroslav@446
   235
    private static Object getProperty(Object object, String property) {
jaroslav@446
   236
        return null;
jaroslav@446
   237
    }
jaroslav@446
   238
    
jaroslav@60
   239
    public static Object parse(InputStream is) throws IOException {
jaroslav@60
   240
        try {
jaroslav@60
   241
            InputStreamReader r = new InputStreamReader(is, "UTF-8");
jaroslav@60
   242
            JSONTokener t = new JSONTokener(r);
jaroslav@60
   243
            return new JSONObject(t);
jaroslav@60
   244
        } catch (JSONException ex) {
jaroslav@60
   245
            throw new IOException(ex);
jaroslav@60
   246
        }
jaroslav@60
   247
    }
jaroslav@37
   248
}