ko-fx/src/test/java/org/apidesign/html/kofx/DynamicHTTP.java
branchnetbeans
changeset 362 92fb71afdc0e
parent 361 700087d2a5d3
child 364 2739565c7a45
     1.1 --- a/ko-fx/src/test/java/org/apidesign/html/kofx/DynamicHTTP.java	Mon Dec 16 15:48:09 2013 +0100
     1.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 @@ -1,259 +0,0 @@
     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.apidesign.html.kofx;
    1.47 -
    1.48 -import java.io.ByteArrayInputStream;
    1.49 -import java.io.ByteArrayOutputStream;
    1.50 -import java.io.IOException;
    1.51 -import java.io.InputStream;
    1.52 -import java.io.OutputStream;
    1.53 -import java.io.Reader;
    1.54 -import java.net.URI;
    1.55 -import java.net.URISyntaxException;
    1.56 -import java.util.ArrayList;
    1.57 -import java.util.List;
    1.58 -import java.util.logging.Level;
    1.59 -import java.util.logging.Logger;
    1.60 -import org.glassfish.grizzly.PortRange;
    1.61 -import org.glassfish.grizzly.http.server.HttpHandler;
    1.62 -import org.glassfish.grizzly.http.server.HttpServer;
    1.63 -import org.glassfish.grizzly.http.server.NetworkListener;
    1.64 -import org.glassfish.grizzly.http.server.Request;
    1.65 -import org.glassfish.grizzly.http.server.Response;
    1.66 -import org.glassfish.grizzly.http.server.ServerConfiguration;
    1.67 -import org.glassfish.grizzly.websockets.WebSocket;
    1.68 -import org.glassfish.grizzly.websockets.WebSocketAddOn;
    1.69 -import org.glassfish.grizzly.websockets.WebSocketApplication;
    1.70 -import org.glassfish.grizzly.websockets.WebSocketEngine;
    1.71 -
    1.72 -/**
    1.73 - *
    1.74 - * @author Jaroslav Tulach <jtulach@netbeans.org>
    1.75 - */
    1.76 -final class DynamicHTTP extends HttpHandler {
    1.77 -    private static final Logger LOG = Logger.getLogger(DynamicHTTP.class.getName());
    1.78 -    private static int resourcesCount;
    1.79 -    private static List<Resource> resources;
    1.80 -    private static ServerConfiguration conf;
    1.81 -    private static HttpServer server;
    1.82 -    
    1.83 -    private DynamicHTTP() {
    1.84 -    }
    1.85 -    
    1.86 -    static URI initServer() throws Exception {
    1.87 -        server = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
    1.88 -        final WebSocketAddOn addon = new WebSocketAddOn();
    1.89 -        for (NetworkListener listener : server.getListeners()) {
    1.90 -            listener.registerAddOn(addon);
    1.91 -        }        
    1.92 -        resources = new ArrayList<Resource>();
    1.93 -
    1.94 -        conf = server.getServerConfiguration();
    1.95 -        final DynamicHTTP dh = new DynamicHTTP();
    1.96 -
    1.97 -        conf.addHttpHandler(dh, "/");
    1.98 -        
    1.99 -        server.start();
   1.100 -
   1.101 -        return pageURL("http", server, "/test.html");
   1.102 -    }
   1.103 -    
   1.104 -    @Override
   1.105 -    public void service(Request request, Response response) throws Exception {
   1.106 -        if ("/test.html".equals(request.getRequestURI())) {
   1.107 -            response.setContentType("text/html");
   1.108 -            final InputStream is = DynamicHTTP.class.getResourceAsStream("test.html");
   1.109 -            copyStream(is, response.getOutputStream(), null);
   1.110 -            return;
   1.111 -        }
   1.112 -        if ("/dynamic".equals(request.getRequestURI())) {
   1.113 -            String mimeType = request.getParameter("mimeType");
   1.114 -            List<String> params = new ArrayList<String>();
   1.115 -            boolean webSocket = false;
   1.116 -            for (int i = 0;; i++) {
   1.117 -                String p = request.getParameter("param" + i);
   1.118 -                if (p == null) {
   1.119 -                    break;
   1.120 -                }
   1.121 -                if ("protocol:ws".equals(p)) {
   1.122 -                    webSocket = true;
   1.123 -                    continue;
   1.124 -                }
   1.125 -                params.add(p);
   1.126 -            }
   1.127 -            final String cnt = request.getParameter("content");
   1.128 -            String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
   1.129 -            ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
   1.130 -            URI url;
   1.131 -            final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
   1.132 -            if (webSocket) {
   1.133 -                url = registerWebSocket(res);
   1.134 -            } else {
   1.135 -                url = registerResource(res);
   1.136 -            }
   1.137 -            response.getWriter().write(url.toString());
   1.138 -            response.getWriter().write("\n");
   1.139 -            return;
   1.140 -        }
   1.141 -
   1.142 -        for (Resource r : resources) {
   1.143 -            if (r.httpPath.equals(request.getRequestURI())) {
   1.144 -                response.setContentType(r.httpType);
   1.145 -                r.httpContent.reset();
   1.146 -                String[] params = null;
   1.147 -                if (r.parameters.length != 0) {
   1.148 -                    params = new String[r.parameters.length];
   1.149 -                    for (int i = 0; i < r.parameters.length; i++) {
   1.150 -                        params[i] = request.getParameter(r.parameters[i]);
   1.151 -                        if (params[i] == null) {
   1.152 -                            if ("http.method".equals(r.parameters[i])) {
   1.153 -                                params[i] = request.getMethod().toString();
   1.154 -                            } else if ("http.requestBody".equals(r.parameters[i])) {
   1.155 -                                Reader rdr = request.getReader();
   1.156 -                                StringBuilder sb = new StringBuilder();
   1.157 -                                for (;;) {
   1.158 -                                    int ch = rdr.read();
   1.159 -                                    if (ch == -1) {
   1.160 -                                        break;
   1.161 -                                    }
   1.162 -                                    sb.append((char) ch);
   1.163 -                                }
   1.164 -                                params[i] = sb.toString();
   1.165 -                            }
   1.166 -                        }
   1.167 -                        if (params[i] == null) {
   1.168 -                            params[i] = "null";
   1.169 -                        }
   1.170 -                    }
   1.171 -                }
   1.172 -
   1.173 -                copyStream(r.httpContent, response.getOutputStream(), null, params);
   1.174 -            }
   1.175 -        }
   1.176 -    }
   1.177 -    
   1.178 -    private URI registerWebSocket(Resource r) {
   1.179 -        WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
   1.180 -        return pageURL("ws", server, r.httpPath);
   1.181 -    }
   1.182 -
   1.183 -    private URI registerResource(Resource r) {
   1.184 -        if (!resources.contains(r)) {
   1.185 -            resources.add(r);
   1.186 -            conf.addHttpHandler(this, r.httpPath);
   1.187 -        }
   1.188 -        return pageURL("http", server, r.httpPath);
   1.189 -    }
   1.190 -    
   1.191 -    private static URI pageURL(String proto, HttpServer server, final String page) {
   1.192 -        NetworkListener listener = server.getListeners().iterator().next();
   1.193 -        int port = listener.getPort();
   1.194 -        try {
   1.195 -            return new URI(proto + "://localhost:" + port + page);
   1.196 -        } catch (URISyntaxException ex) {
   1.197 -            throw new IllegalStateException(ex);
   1.198 -        }
   1.199 -    }
   1.200 -    
   1.201 -    static final class Resource {
   1.202 -
   1.203 -        final InputStream httpContent;
   1.204 -        final String httpType;
   1.205 -        final String httpPath;
   1.206 -        final String[] parameters;
   1.207 -
   1.208 -        Resource(InputStream httpContent, String httpType, String httpPath,
   1.209 -            String[] parameters) {
   1.210 -            httpContent.mark(Integer.MAX_VALUE);
   1.211 -            this.httpContent = httpContent;
   1.212 -            this.httpType = httpType;
   1.213 -            this.httpPath = httpPath;
   1.214 -            this.parameters = parameters;
   1.215 -        }
   1.216 -    }
   1.217 -
   1.218 -    static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   1.219 -        for (;;) {
   1.220 -            int ch = is.read();
   1.221 -            if (ch == -1) {
   1.222 -                break;
   1.223 -            }
   1.224 -            if (ch == '$' && params.length > 0) {
   1.225 -                int cnt = is.read() - '0';
   1.226 -                if (baseURL != null && cnt == 'U' - '0') {
   1.227 -                    os.write(baseURL.getBytes("UTF-8"));
   1.228 -                } else {
   1.229 -                    if (cnt >= 0 && cnt < params.length) {
   1.230 -                        os.write(params[cnt].getBytes("UTF-8"));
   1.231 -                    } else {
   1.232 -                        os.write('$');
   1.233 -                        os.write(cnt + '0');
   1.234 -                    }
   1.235 -                }
   1.236 -            } else {
   1.237 -                os.write(ch);
   1.238 -            }
   1.239 -        }
   1.240 -    }
   1.241 -    
   1.242 -    private static class WS extends WebSocketApplication {
   1.243 -        private final Resource r;
   1.244 -
   1.245 -        private WS(Resource r) {
   1.246 -            this.r = r;
   1.247 -        }
   1.248 -
   1.249 -        @Override
   1.250 -        public void onMessage(WebSocket socket, String text) {
   1.251 -            try {
   1.252 -                r.httpContent.reset();
   1.253 -                ByteArrayOutputStream out = new ByteArrayOutputStream();
   1.254 -                copyStream(r.httpContent, out, null, text);
   1.255 -                String s = new String(out.toByteArray(), "UTF-8");
   1.256 -                socket.send(s);
   1.257 -            } catch (IOException ex) {
   1.258 -                LOG.log(Level.WARNING, "Error processing message " + text, ex);
   1.259 -            }
   1.260 -        }
   1.261 -    }
   1.262 -}