ko-ws-tyrus/src/main/java/org/netbeans/html/wstyrus/TyrusContext.java
author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
Thu, 09 Jan 2014 20:39:23 +0100
branchUniversalKO
changeset 446 6dce58c06f58
parent 365 5c93ad8c7a15
child 468 fba23d542271
child 470 63218f926a49
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@260
     1
/**
jaroslav@358
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jaroslav@260
     3
 *
jaroslav@365
     4
 * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
jaroslav@260
     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@260
     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@260
    42
 */
jaroslav@362
    43
package org.netbeans.html.wstyrus;
jaroslav@260
    44
jaroslav@260
    45
import java.io.IOException;
jaroslav@446
    46
import java.io.InputStream;
jaroslav@260
    47
import java.net.URI;
jaroslav@260
    48
import java.net.URISyntaxException;
jaroslav@260
    49
import java.util.Iterator;
jaroslav@260
    50
import javax.websocket.ClientEndpoint;
jaroslav@260
    51
import javax.websocket.ContainerProvider;
jaroslav@260
    52
import javax.websocket.DeploymentException;
jaroslav@260
    53
import javax.websocket.OnClose;
jaroslav@260
    54
import javax.websocket.OnError;
jaroslav@260
    55
import javax.websocket.OnMessage;
jaroslav@260
    56
import javax.websocket.OnOpen;
jaroslav@260
    57
import javax.websocket.Session;
jaroslav@260
    58
import javax.websocket.WebSocketContainer;
jaroslav@263
    59
import net.java.html.json.OnReceive;
jaroslav@260
    60
import org.apidesign.html.context.spi.Contexts;
jaroslav@260
    61
import org.apidesign.html.json.spi.JSONCall;
jaroslav@446
    62
import org.apidesign.html.json.spi.Technology;
jaroslav@446
    63
import org.apidesign.html.json.spi.Transfer;
jaroslav@260
    64
import org.apidesign.html.json.spi.WSTransfer;
jaroslav@362
    65
import org.netbeans.html.wstyrus.TyrusContext.Comm;
jaroslav@260
    66
import org.json.JSONArray;
jaroslav@260
    67
import org.json.JSONException;
jaroslav@260
    68
import org.json.JSONObject;
jaroslav@260
    69
import org.json.JSONTokener;
jaroslav@260
    70
import org.openide.util.lookup.ServiceProvider;
jaroslav@260
    71
jaroslav@263
    72
/** This is an implementation module that provides support for
jaroslav@263
    73
 * WebSocket protocol for {@link OnReceive} communication end point for
jaroslav@263
    74
 * JDK7.
jaroslav@263
    75
 * <p>
jaroslav@263
    76
 * Don't deal with this module directly, rather use the 
jaroslav@263
    77
 * {@link OnReceive @OnReceive(url="ws://...", ...)} API to establish your
jaroslav@263
    78
 * WebSocket connection.
jaroslav@263
    79
 * <p>
jaroslav@263
    80
 * There is no need to include this module in your application if you are
jaroslav@263
    81
 * running on JDK8. JDK8 WebView provides its own implementation of the
jaroslav@263
    82
 * WebSocket API based on WebSocket object inside a browser. This is included
jaroslav@263
    83
 * in the <code>org.apidesign.html:ko-fx:0.5</code> module.
jaroslav@260
    84
 *
jaroslav@260
    85
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jaroslav@260
    86
 */
jaroslav@260
    87
@ServiceProvider(service = Contexts.Provider.class)
jaroslav@446
    88
public final class TyrusContext 
jaroslav@446
    89
implements Contexts.Provider, WSTransfer<Comm>, Transfer {
jaroslav@260
    90
    @Override
jaroslav@260
    91
    public void fillContext(Contexts.Builder context, Class<?> requestor) {
jaroslav@260
    92
        // default WebSocket transfer implementation is registered
jaroslav@260
    93
        // in ko-fx module with 100, provide this one as a fallback only
jaroslav@260
    94
        context.register(WSTransfer.class, this, 1000);
jaroslav@446
    95
        context.register(Transfer.class, this, 1000);
jaroslav@260
    96
    }
jaroslav@260
    97
jaroslav@260
    98
    @Override
jaroslav@260
    99
    public Comm open(String url, JSONCall callback) {
jaroslav@260
   100
        try {
jaroslav@260
   101
            return new Comm(new URI(url), callback);
jaroslav@260
   102
        } catch (URISyntaxException ex) {
jaroslav@260
   103
            throw new IllegalStateException(ex);
jaroslav@260
   104
        }
jaroslav@260
   105
    }
jaroslav@260
   106
jaroslav@260
   107
    @Override
jaroslav@260
   108
    public void send(Comm socket, JSONCall data) {
jaroslav@260
   109
        socket.session.getAsyncRemote().sendText(data.getMessage());
jaroslav@260
   110
    }
jaroslav@260
   111
jaroslav@260
   112
    @Override
jaroslav@260
   113
    public void close(Comm socket) {
jaroslav@260
   114
        try {
jaroslav@269
   115
            final Session s = socket.session;
jaroslav@269
   116
            if (s != null) {
jaroslav@269
   117
                s.close();
jaroslav@269
   118
            }
jaroslav@260
   119
        } catch (IOException ex) {
jaroslav@260
   120
            socket.callback.notifyError(ex);
jaroslav@260
   121
        }
jaroslav@260
   122
    }
jaroslav@446
   123
jaroslav@446
   124
    @Override
jaroslav@446
   125
    public void extract(Object obj, String[] props, Object[] values) {
jaroslav@446
   126
        LoadJSON.extractJSON(obj, props, values);
jaroslav@446
   127
    }
jaroslav@446
   128
jaroslav@446
   129
    @Override
jaroslav@446
   130
    public Object toJSON(InputStream is) throws IOException {
jaroslav@446
   131
        return LoadJSON.parse(is);
jaroslav@446
   132
    }
jaroslav@446
   133
jaroslav@446
   134
    @Override
jaroslav@446
   135
    public void loadJSON(JSONCall call) {
jaroslav@446
   136
        LoadJSON.loadJSON(call);
jaroslav@446
   137
    }
jaroslav@260
   138
    
jaroslav@263
   139
    /** Implementation class in an implementation. Represents a {@link ClientEndpoint} of the
jaroslav@263
   140
     * WebSocket channel. You are unlikely to get on hold of it.
jaroslav@263
   141
     */
jaroslav@260
   142
    @ClientEndpoint
jaroslav@260
   143
    public static final class Comm {
jaroslav@260
   144
        private final JSONCall callback;
jaroslav@260
   145
        private Session session;
jaroslav@260
   146
jaroslav@260
   147
        Comm(final URI url, JSONCall callback) {
jaroslav@260
   148
            this.callback = callback;
jaroslav@260
   149
            try {
jaroslav@260
   150
                final WebSocketContainer c = ContainerProvider.getWebSocketContainer();
jaroslav@260
   151
                c.connectToServer(Comm.this, url);
jaroslav@260
   152
            } catch (DeploymentException | IOException ex) {
jaroslav@260
   153
                wasAnError(ex);
jaroslav@260
   154
            }
jaroslav@260
   155
        }
jaroslav@260
   156
jaroslav@260
   157
        @OnOpen
jaroslav@260
   158
        public synchronized void open(Session s) {
jaroslav@260
   159
            this.session = s;
jaroslav@260
   160
            callback.notifySuccess(null);
jaroslav@260
   161
        }
jaroslav@260
   162
jaroslav@260
   163
        @OnClose
jaroslav@260
   164
        public void close() {
jaroslav@260
   165
            this.session = null;
jaroslav@260
   166
            callback.notifyError(null);
jaroslav@260
   167
        }
jaroslav@260
   168
jaroslav@260
   169
        @OnMessage
jaroslav@260
   170
        public void message(final String orig, Session s) {
jaroslav@262
   171
            Object json;
jaroslav@262
   172
            String data = orig.trim();
jaroslav@262
   173
            try {
jaroslav@262
   174
                JSONTokener tok = new JSONTokener(data);
jaroslav@262
   175
                Object obj = data.startsWith("[") ? new JSONArray(tok) : new JSONObject(tok);
jaroslav@262
   176
                json = convertToArray(obj);
jaroslav@262
   177
            } catch (JSONException ex) {
jaroslav@262
   178
                json = data;
jaroslav@260
   179
            }
jaroslav@262
   180
            callback.notifySuccess(json);
jaroslav@260
   181
        }
jaroslav@260
   182
jaroslav@260
   183
        @OnError
jaroslav@260
   184
        public void wasAnError(Throwable t) {
jaroslav@260
   185
            callback.notifyError(t);
jaroslav@260
   186
        }
jaroslav@260
   187
jaroslav@260
   188
        static Object convertToArray(Object o) throws JSONException {
jaroslav@260
   189
            if (o instanceof JSONArray) {
jaroslav@260
   190
                JSONArray ja = (JSONArray) o;
jaroslav@260
   191
                Object[] arr = new Object[ja.length()];
jaroslav@260
   192
                for (int i = 0; i < arr.length; i++) {
jaroslav@260
   193
                    arr[i] = convertToArray(ja.get(i));
jaroslav@260
   194
                }
jaroslav@260
   195
                return arr;
jaroslav@260
   196
            } else if (o instanceof JSONObject) {
jaroslav@260
   197
                JSONObject obj = (JSONObject) o;
jaroslav@260
   198
                Iterator it = obj.keys();
jaroslav@260
   199
                while (it.hasNext()) {
jaroslav@260
   200
                    String key = (String) it.next();
jaroslav@260
   201
                    obj.put(key, convertToArray(obj.get(key)));
jaroslav@260
   202
                }
jaroslav@260
   203
                return obj;
jaroslav@260
   204
            } else {
jaroslav@260
   205
                return o;
jaroslav@260
   206
            }
jaroslav@260
   207
        }
jaroslav@260
   208
        
jaroslav@260
   209
    } // end of Comm
jaroslav@260
   210
}