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