ko-ws-tyrus/src/main/java/org/netbeans/html/wstyrus/TyrusContext.java
branchnetbeans
changeset 362 92fb71afdc0e
parent 358 80702021b851
child 365 5c93ad8c7a15
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/ko-ws-tyrus/src/main/java/org/netbeans/html/wstyrus/TyrusContext.java	Mon Dec 16 16:59:43 2013 +0100
     1.3 @@ -0,0 +1,190 @@
     1.4 +/**
     1.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     1.6 + *
     1.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
     1.8 + *
     1.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
    1.10 + * Other names may be trademarks of their respective owners.
    1.11 + *
    1.12 + * The contents of this file are subject to the terms of either the GNU
    1.13 + * General Public License Version 2 only ("GPL") or the Common
    1.14 + * Development and Distribution License("CDDL") (collectively, the
    1.15 + * "License"). You may not use this file except in compliance with the
    1.16 + * License. You can obtain a copy of the License at
    1.17 + * http://www.netbeans.org/cddl-gplv2.html
    1.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    1.19 + * specific language governing permissions and limitations under the
    1.20 + * License.  When distributing the software, include this License Header
    1.21 + * Notice in each file and include the License file at
    1.22 + * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    1.23 + * particular file as subject to the "Classpath" exception as provided
    1.24 + * by Oracle in the GPL Version 2 section of the License file that
    1.25 + * accompanied this code. If applicable, add the following below the
    1.26 + * License Header, with the fields enclosed by brackets [] replaced by
    1.27 + * your own identifying information:
    1.28 + * "Portions Copyrighted [year] [name of copyright owner]"
    1.29 + *
    1.30 + * Contributor(s):
    1.31 + *
    1.32 + * The Original Software is NetBeans. The Initial Developer of the Original
    1.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
    1.34 + *
    1.35 + * If you wish your version of this file to be governed by only the CDDL
    1.36 + * or only the GPL Version 2, indicate your decision by adding
    1.37 + * "[Contributor] elects to include this software in this distribution
    1.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
    1.39 + * single choice of license, a recipient has the option to distribute
    1.40 + * your version of this file under either the CDDL, the GPL Version 2 or
    1.41 + * to extend the choice of license to its licensees as provided above.
    1.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
    1.43 + * Version 2 license, then the option applies only if the new code is
    1.44 + * made subject to such option by the copyright holder.
    1.45 + */
    1.46 +package org.netbeans.html.wstyrus;
    1.47 +
    1.48 +import java.io.IOException;
    1.49 +import java.net.URI;
    1.50 +import java.net.URISyntaxException;
    1.51 +import java.util.Iterator;
    1.52 +import javax.websocket.ClientEndpoint;
    1.53 +import javax.websocket.ContainerProvider;
    1.54 +import javax.websocket.DeploymentException;
    1.55 +import javax.websocket.OnClose;
    1.56 +import javax.websocket.OnError;
    1.57 +import javax.websocket.OnMessage;
    1.58 +import javax.websocket.OnOpen;
    1.59 +import javax.websocket.Session;
    1.60 +import javax.websocket.WebSocketContainer;
    1.61 +import net.java.html.json.OnReceive;
    1.62 +import org.apidesign.html.context.spi.Contexts;
    1.63 +import org.apidesign.html.json.spi.JSONCall;
    1.64 +import org.apidesign.html.json.spi.WSTransfer;
    1.65 +import org.netbeans.html.wstyrus.TyrusContext.Comm;
    1.66 +import org.json.JSONArray;
    1.67 +import org.json.JSONException;
    1.68 +import org.json.JSONObject;
    1.69 +import org.json.JSONTokener;
    1.70 +import org.openide.util.lookup.ServiceProvider;
    1.71 +
    1.72 +/** This is an implementation module that provides support for
    1.73 + * WebSocket protocol for {@link OnReceive} communication end point for
    1.74 + * JDK7.
    1.75 + * <p>
    1.76 + * Don't deal with this module directly, rather use the 
    1.77 + * {@link OnReceive @OnReceive(url="ws://...", ...)} API to establish your
    1.78 + * WebSocket connection.
    1.79 + * <p>
    1.80 + * There is no need to include this module in your application if you are
    1.81 + * running on JDK8. JDK8 WebView provides its own implementation of the
    1.82 + * WebSocket API based on WebSocket object inside a browser. This is included
    1.83 + * in the <code>org.apidesign.html:ko-fx:0.5</code> module.
    1.84 + *
    1.85 + * @author Jaroslav Tulach <jtulach@netbeans.org>
    1.86 + */
    1.87 +@ServiceProvider(service = Contexts.Provider.class)
    1.88 +public final class TyrusContext implements Contexts.Provider, WSTransfer<Comm> {
    1.89 +    @Override
    1.90 +    public void fillContext(Contexts.Builder context, Class<?> requestor) {
    1.91 +        // default WebSocket transfer implementation is registered
    1.92 +        // in ko-fx module with 100, provide this one as a fallback only
    1.93 +        context.register(WSTransfer.class, this, 1000);
    1.94 +    }
    1.95 +
    1.96 +    @Override
    1.97 +    public Comm open(String url, JSONCall callback) {
    1.98 +        try {
    1.99 +            return new Comm(new URI(url), callback);
   1.100 +        } catch (URISyntaxException ex) {
   1.101 +            throw new IllegalStateException(ex);
   1.102 +        }
   1.103 +    }
   1.104 +
   1.105 +    @Override
   1.106 +    public void send(Comm socket, JSONCall data) {
   1.107 +        socket.session.getAsyncRemote().sendText(data.getMessage());
   1.108 +    }
   1.109 +
   1.110 +    @Override
   1.111 +    public void close(Comm socket) {
   1.112 +        try {
   1.113 +            final Session s = socket.session;
   1.114 +            if (s != null) {
   1.115 +                s.close();
   1.116 +            }
   1.117 +        } catch (IOException ex) {
   1.118 +            socket.callback.notifyError(ex);
   1.119 +        }
   1.120 +    }
   1.121 +    
   1.122 +    /** Implementation class in an implementation. Represents a {@link ClientEndpoint} of the
   1.123 +     * WebSocket channel. You are unlikely to get on hold of it.
   1.124 +     */
   1.125 +    @ClientEndpoint
   1.126 +    public static final class Comm {
   1.127 +        private final JSONCall callback;
   1.128 +        private Session session;
   1.129 +
   1.130 +        Comm(final URI url, JSONCall callback) {
   1.131 +            this.callback = callback;
   1.132 +            try {
   1.133 +                final WebSocketContainer c = ContainerProvider.getWebSocketContainer();
   1.134 +                c.connectToServer(Comm.this, url);
   1.135 +            } catch (DeploymentException | IOException ex) {
   1.136 +                wasAnError(ex);
   1.137 +            }
   1.138 +        }
   1.139 +
   1.140 +        @OnOpen
   1.141 +        public synchronized void open(Session s) {
   1.142 +            this.session = s;
   1.143 +            callback.notifySuccess(null);
   1.144 +        }
   1.145 +
   1.146 +        @OnClose
   1.147 +        public void close() {
   1.148 +            this.session = null;
   1.149 +            callback.notifyError(null);
   1.150 +        }
   1.151 +
   1.152 +        @OnMessage
   1.153 +        public void message(final String orig, Session s) {
   1.154 +            Object json;
   1.155 +            String data = orig.trim();
   1.156 +            try {
   1.157 +                JSONTokener tok = new JSONTokener(data);
   1.158 +                Object obj = data.startsWith("[") ? new JSONArray(tok) : new JSONObject(tok);
   1.159 +                json = convertToArray(obj);
   1.160 +            } catch (JSONException ex) {
   1.161 +                json = data;
   1.162 +            }
   1.163 +            callback.notifySuccess(json);
   1.164 +        }
   1.165 +
   1.166 +        @OnError
   1.167 +        public void wasAnError(Throwable t) {
   1.168 +            callback.notifyError(t);
   1.169 +        }
   1.170 +
   1.171 +        static Object convertToArray(Object o) throws JSONException {
   1.172 +            if (o instanceof JSONArray) {
   1.173 +                JSONArray ja = (JSONArray) o;
   1.174 +                Object[] arr = new Object[ja.length()];
   1.175 +                for (int i = 0; i < arr.length; i++) {
   1.176 +                    arr[i] = convertToArray(ja.get(i));
   1.177 +                }
   1.178 +                return arr;
   1.179 +            } else if (o instanceof JSONObject) {
   1.180 +                JSONObject obj = (JSONObject) o;
   1.181 +                Iterator it = obj.keys();
   1.182 +                while (it.hasNext()) {
   1.183 +                    String key = (String) it.next();
   1.184 +                    obj.put(key, convertToArray(obj.get(key)));
   1.185 +                }
   1.186 +                return obj;
   1.187 +            } else {
   1.188 +                return o;
   1.189 +            }
   1.190 +        }
   1.191 +        
   1.192 +    } // end of Comm
   1.193 +}