ko-ws-tyrus/src/main/java/org/netbeans/html/wstyrus/LoadJSON.java
author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
Fri, 07 Feb 2014 07:44:34 +0100
changeset 551 7ca2253fa86d
parent 527 77a424a04c62
child 745 4f12b1d9c695
permissions -rw-r--r--
Updating copyright headers to mention current year
jaroslav@37
     1
/**
jaroslav@358
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jaroslav@37
     3
 *
jaroslav@551
     4
 * Copyright 2013-2014 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@551
    30
 * Software is Oracle. Portions Copyright 2013-2014 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.URL;
jaroslav@74
    53
import java.net.URLConnection;
jaroslav@37
    54
import java.util.Iterator;
jaroslav@37
    55
import java.util.concurrent.Executor;
jaroslav@37
    56
import java.util.concurrent.Executors;
jaroslav@158
    57
import java.util.concurrent.ThreadFactory;
jaroslav@37
    58
import java.util.logging.Level;
jaroslav@37
    59
import java.util.logging.Logger;
jaroslav@131
    60
import net.java.html.js.JavaScriptBody;
jaroslav@37
    61
import org.apidesign.html.json.spi.JSONCall;
jaroslav@37
    62
import org.json.JSONArray;
jaroslav@37
    63
import org.json.JSONException;
jaroslav@37
    64
import org.json.JSONObject;
jaroslav@37
    65
import org.json.JSONTokener;
jaroslav@37
    66
jaroslav@54
    67
/** This is an implementation package - just
jaroslav@54
    68
 * include its JAR on classpath and use official {@link Context} API
jaroslav@54
    69
 * to access the functionality.
jaroslav@37
    70
 *
jaroslav@37
    71
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jaroslav@37
    72
 */
jaroslav@37
    73
final class LoadJSON implements Runnable {
jaroslav@446
    74
    private static final Logger LOG = Logger.getLogger(LoadJSON.class.getName());
jaroslav@158
    75
    private static final Executor REQ = Executors.newCachedThreadPool(new ThreadFactory() {
jaroslav@158
    76
        @Override
jaroslav@158
    77
        public Thread newThread(Runnable runnable) {
jaroslav@158
    78
            Thread thread = Executors.defaultThreadFactory().newThread(runnable);
jaroslav@158
    79
            thread.setDaemon(true);
jaroslav@158
    80
            return thread;
jaroslav@158
    81
        }
jaroslav@158
    82
    });
jaroslav@37
    83
jaroslav@37
    84
    private final JSONCall call;
jaroslav@37
    85
    private final URL base;
jaroslav@37
    86
jaroslav@37
    87
jaroslav@37
    88
    private LoadJSON(JSONCall call) {
jaroslav@37
    89
        this.call = call;
jaroslav@446
    90
        this.base = null;
jaroslav@37
    91
    }
jaroslav@37
    92
jaroslav@37
    93
    public static void loadJSON(JSONCall call) {
jaroslav@258
    94
        assert !"WebSocket".equals(call.getMethod());
jaroslav@258
    95
        REQ.execute(new LoadJSON((call)));
jaroslav@37
    96
    }
jaroslav@37
    97
jaroslav@37
    98
    @Override
jaroslav@37
    99
    public void run() {
jaroslav@37
   100
        final String url;
jaroslav@446
   101
        Throwable error = null;
jaroslav@446
   102
        Object json = null;
jaroslav@446
   103
        
jaroslav@37
   104
        if (call.isJSONP()) {
jaroslav@37
   105
            url = call.composeURL("dummy");
jaroslav@37
   106
        } else {
jaroslav@37
   107
            url = call.composeURL(null);
jaroslav@37
   108
        }
jaroslav@37
   109
        try {
jaroslav@37
   110
            final URL u = new URL(base, url.replace(" ", "%20"));
jaroslav@74
   111
            URLConnection conn = u.openConnection();
jaroslav@527
   112
            if (call.isDoOutput()) {
jaroslav@527
   113
                conn.setDoOutput(true);
jaroslav@527
   114
            }
jaroslav@527
   115
            if (call.getMethod() != null && conn instanceof HttpURLConnection) {
jaroslav@527
   116
                ((HttpURLConnection) conn).setRequestMethod(call.getMethod());
jaroslav@527
   117
            }
jaroslav@527
   118
            if (call.isDoOutput()) {
jaroslav@527
   119
                final OutputStream os = conn.getOutputStream();
jaroslav@527
   120
                call.writeData(os);
jaroslav@527
   121
                os.flush();
jaroslav@74
   122
            }
jaroslav@74
   123
            final PushbackInputStream is = new PushbackInputStream(
jaroslav@74
   124
                conn.getInputStream(), 1
jaroslav@74
   125
            );
jaroslav@37
   126
            boolean array = false;
jaroslav@73
   127
            boolean string = false;
jaroslav@37
   128
            if (call.isJSONP()) {
jaroslav@37
   129
                for (;;) {
jaroslav@37
   130
                    int ch = is.read();
jaroslav@37
   131
                    if (ch == -1) {
jaroslav@37
   132
                        break;
jaroslav@37
   133
                    }
jaroslav@37
   134
                    if (ch == '[') {
jaroslav@37
   135
                        is.unread(ch);
jaroslav@37
   136
                        array = true;
jaroslav@37
   137
                        break;
jaroslav@37
   138
                    }
jaroslav@37
   139
                    if (ch == '{') {
jaroslav@37
   140
                        is.unread(ch);
jaroslav@37
   141
                        break;
jaroslav@37
   142
                    }
jaroslav@37
   143
                }
jaroslav@37
   144
            } else {
jaroslav@37
   145
                int ch = is.read();
jaroslav@138
   146
                if (ch == -1) {
jaroslav@73
   147
                    string = true;
jaroslav@138
   148
                } else {
jaroslav@138
   149
                    array = ch == '[';
jaroslav@138
   150
                    is.unread(ch);
jaroslav@138
   151
                    if (!array && ch != '{') {
jaroslav@138
   152
                        string = true;
jaroslav@138
   153
                    }
jaroslav@73
   154
                }
jaroslav@37
   155
            }
jaroslav@73
   156
            try {
jaroslav@73
   157
                if (string) {
jaroslav@73
   158
                    throw new JSONException("");
jaroslav@73
   159
                }
jaroslav@525
   160
                JSONTokener tok = createTokener(is);
jaroslav@73
   161
                Object obj;
jaroslav@73
   162
                obj = array ? new JSONArray(tok) : new JSONObject(tok);
jaroslav@73
   163
                json = convertToArray(obj);
jaroslav@73
   164
            } catch (JSONException ex) {
jaroslav@73
   165
                Reader r = new InputStreamReader(is, "UTF-8");
jaroslav@73
   166
                StringBuilder sb = new StringBuilder();
jaroslav@73
   167
                for (;;) {
jaroslav@73
   168
                    int ch = r.read();
jaroslav@73
   169
                    if (ch == -1) {
jaroslav@73
   170
                        break;
jaroslav@73
   171
                    }
jaroslav@73
   172
                    sb.append((char)ch);
jaroslav@73
   173
                }
jaroslav@73
   174
                json = sb.toString();
jaroslav@73
   175
            }
jaroslav@73
   176
        } catch (IOException ex) {
jaroslav@37
   177
            error = ex;
jaroslav@37
   178
        } finally {
jaroslav@446
   179
            if (error != null) {
jaroslav@446
   180
                call.notifyError(error);
jaroslav@446
   181
            } else {
jaroslav@446
   182
                call.notifySuccess(json);
jaroslav@446
   183
            }
jaroslav@37
   184
        }
jaroslav@37
   185
    }
jaroslav@37
   186
jaroslav@525
   187
    private static JSONTokener createTokener(InputStream is) throws IOException {
jaroslav@525
   188
        Reader r = new InputStreamReader(is, "UTF-8");
jaroslav@525
   189
        try {
jaroslav@525
   190
            return new JSONTokener(r);
jaroslav@525
   191
        } catch (LinkageError ex) {
jaroslav@525
   192
            // phones may carry outdated version of JSONTokener
jaroslav@525
   193
            StringBuilder sb = new StringBuilder();
jaroslav@525
   194
            for (;;) {
jaroslav@525
   195
                int ch = r.read();
jaroslav@525
   196
                if (ch == -1) {
jaroslav@525
   197
                    break;
jaroslav@525
   198
                }
jaroslav@525
   199
                sb.append((char)ch);
jaroslav@525
   200
            }
jaroslav@525
   201
            return new JSONTokener(sb.toString());
jaroslav@525
   202
        }
jaroslav@525
   203
    }
jaroslav@525
   204
jaroslav@247
   205
    static Object convertToArray(Object o) throws JSONException {
jaroslav@37
   206
        if (o instanceof JSONArray) {
jaroslav@37
   207
            JSONArray ja = (JSONArray)o;
jaroslav@37
   208
            Object[] arr = new Object[ja.length()];
jaroslav@37
   209
            for (int i = 0; i < arr.length; i++) {
jaroslav@37
   210
                arr[i] = convertToArray(ja.get(i));
jaroslav@37
   211
            }
jaroslav@37
   212
            return arr;
jaroslav@37
   213
        } else if (o instanceof JSONObject) {
jaroslav@37
   214
            JSONObject obj = (JSONObject)o;
jaroslav@37
   215
            Iterator it = obj.keys();
jaroslav@37
   216
            while (it.hasNext()) {
jaroslav@37
   217
                String key = (String)it.next();
jaroslav@37
   218
                obj.put(key, convertToArray(obj.get(key)));
jaroslav@37
   219
            }
jaroslav@37
   220
            return obj;
jaroslav@37
   221
        } else {
jaroslav@37
   222
            return o;
jaroslav@37
   223
        }
jaroslav@37
   224
    }
jaroslav@37
   225
    
jaroslav@37
   226
    public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
jaroslav@37
   227
        if (jsonObject instanceof JSONObject) {
jaroslav@37
   228
            JSONObject obj = (JSONObject)jsonObject;
jaroslav@37
   229
            for (int i = 0; i < props.length; i++) {
jaroslav@37
   230
                try {
jaroslav@37
   231
                    values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
jaroslav@37
   232
                } catch (JSONException ex) {
jaroslav@37
   233
                    LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
jaroslav@37
   234
                }
jaroslav@37
   235
            }
jaroslav@446
   236
            return;
jaroslav@37
   237
        }
jaroslav@446
   238
        for (int i = 0; i < props.length; i++) {
jaroslav@446
   239
            values[i] = getProperty(jsonObject, props[i]);
jaroslav@37
   240
        }
jaroslav@37
   241
    }
jaroslav@37
   242
    
jaroslav@446
   243
    @JavaScriptBody(args = {"object", "property"},
jaroslav@446
   244
            body
jaroslav@446
   245
            = "if (property === null) return object;\n"
jaroslav@446
   246
            + "if (object === null) return null;\n"
jaroslav@446
   247
            + "var p = object[property]; return p ? p : null;"
jaroslav@446
   248
    )
jaroslav@446
   249
    private static Object getProperty(Object object, String property) {
jaroslav@446
   250
        return null;
jaroslav@446
   251
    }
jaroslav@446
   252
    
jaroslav@60
   253
    public static Object parse(InputStream is) throws IOException {
jaroslav@60
   254
        try {
jaroslav@525
   255
            JSONTokener t = createTokener(is);
jaroslav@60
   256
            return new JSONObject(t);
jaroslav@60
   257
        } catch (JSONException ex) {
jaroslav@60
   258
            throw new IOException(ex);
jaroslav@60
   259
        }
jaroslav@60
   260
    }
jaroslav@37
   261
}