xhr4j/src/test/java/org/netbeans/html/xhr4j/JsonDynamicHTTP.java
branchxhr4j
changeset 1057 b547f8f663f5
parent 940 bdec4103bdb2
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/xhr4j/src/test/java/org/netbeans/html/xhr4j/JsonDynamicHTTP.java	Mon Feb 29 05:25:31 2016 +0100
     1.3 @@ -0,0 +1,262 @@
     1.4 +/**
     1.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     1.6 + *
     1.7 + * Copyright 2013-2014 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-2014 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.xhr4j;
    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
    1.75 + */
    1.76 +final class JsonDynamicHTTP extends HttpHandler {
    1.77 +    private static int resourcesCount;
    1.78 +    private static List<Resource> resources;
    1.79 +    private static ServerConfiguration conf;
    1.80 +    private static HttpServer server;
    1.81 +
    1.82 +    private JsonDynamicHTTP() {
    1.83 +    }
    1.84 +
    1.85 +    static URI initServer() throws Exception {
    1.86 +        server = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
    1.87 +        final WebSocketAddOn addon = new WebSocketAddOn();
    1.88 +        for (NetworkListener listener : server.getListeners()) {
    1.89 +            listener.registerAddOn(addon);
    1.90 +        }
    1.91 +        resources = new ArrayList<Resource>();
    1.92 +
    1.93 +        conf = server.getServerConfiguration();
    1.94 +        final JsonDynamicHTTP dh = new JsonDynamicHTTP();
    1.95 +
    1.96 +        conf.addHttpHandler(dh, "/");
    1.97 +
    1.98 +        server.start();
    1.99 +
   1.100 +        return pageURL("http", server, "/test.html");
   1.101 +    }
   1.102 +
   1.103 +    @Override
   1.104 +    public void service(Request request, Response response) throws Exception {
   1.105 +        if ("/test.html".equals(request.getRequestURI())) {
   1.106 +            response.setContentType("text/html");
   1.107 +            final InputStream is = JsonDynamicHTTP.class.getResourceAsStream("test.html");
   1.108 +            copyStream(is, response.getOutputStream(), null);
   1.109 +            return;
   1.110 +        }
   1.111 +        if ("/dynamic".equals(request.getRequestURI())) {
   1.112 +            String mimeType = request.getParameter("mimeType");
   1.113 +            List<String> params = new ArrayList<String>();
   1.114 +            boolean webSocket = false;
   1.115 +            for (int i = 0;; i++) {
   1.116 +                String p = request.getParameter("param" + i);
   1.117 +                if (p == null) {
   1.118 +                    break;
   1.119 +                }
   1.120 +                if ("protocol:ws".equals(p)) {
   1.121 +                    webSocket = true;
   1.122 +                    continue;
   1.123 +                }
   1.124 +                params.add(p);
   1.125 +            }
   1.126 +            final String cnt = request.getParameter("content");
   1.127 +            String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
   1.128 +            ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
   1.129 +            URI url;
   1.130 +            final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
   1.131 +            if (webSocket) {
   1.132 +                url = registerWebSocket(res);
   1.133 +            } else {
   1.134 +                url = registerResource(res);
   1.135 +            }
   1.136 +            response.getWriter().write(url.toString());
   1.137 +            response.getWriter().write("\n");
   1.138 +            return;
   1.139 +        }
   1.140 +
   1.141 +        for (Resource r : resources) {
   1.142 +            if (r.httpPath.equals(request.getRequestURI())) {
   1.143 +                response.setContentType(r.httpType);
   1.144 +                r.httpContent.reset();
   1.145 +                String[] params = null;
   1.146 +                if (r.parameters.length != 0) {
   1.147 +                    params = new String[r.parameters.length];
   1.148 +                    for (int i = 0; i < r.parameters.length; i++) {
   1.149 +                        params[i] = request.getParameter(r.parameters[i]);
   1.150 +                        if (params[i] == null) {
   1.151 +                            if ("http.method".equals(r.parameters[i])) {
   1.152 +                                params[i] = request.getMethod().toString();
   1.153 +                            } else if ("http.requestBody".equals(r.parameters[i])) {
   1.154 +                                Reader rdr = request.getReader();
   1.155 +                                StringBuilder sb = new StringBuilder();
   1.156 +                                for (;;) {
   1.157 +                                    int ch = rdr.read();
   1.158 +                                    if (ch == -1) {
   1.159 +                                        break;
   1.160 +                                    }
   1.161 +                                    sb.append((char) ch);
   1.162 +                                }
   1.163 +                                params[i] = sb.toString();
   1.164 +                            } else if (r.parameters[i].startsWith("http.header.")) {
   1.165 +                                params[i] = request.getHeader(r.parameters[i].substring(12));
   1.166 +                            }
   1.167 +                        }
   1.168 +                        if (params[i] == null) {
   1.169 +                            params[i] = "null";
   1.170 +                        }
   1.171 +                    }
   1.172 +                }
   1.173 +
   1.174 +                copyStream(r.httpContent, response.getOutputStream(), null, params);
   1.175 +            }
   1.176 +        }
   1.177 +    }
   1.178 +
   1.179 +    private URI registerWebSocket(Resource r) {
   1.180 +        WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
   1.181 +        return pageURL("ws", server, r.httpPath);
   1.182 +    }
   1.183 +
   1.184 +    private URI registerResource(Resource r) {
   1.185 +        if (!resources.contains(r)) {
   1.186 +            resources.add(r);
   1.187 +            conf.addHttpHandler(this, r.httpPath);
   1.188 +        }
   1.189 +        return pageURL("http", server, r.httpPath);
   1.190 +    }
   1.191 +
   1.192 +    private static URI pageURL(String proto, HttpServer server, final String page) {
   1.193 +        NetworkListener listener = server.getListeners().iterator().next();
   1.194 +        int port = listener.getPort();
   1.195 +        try {
   1.196 +            return new URI(proto + "://localhost:" + port + page);
   1.197 +        } catch (URISyntaxException ex) {
   1.198 +            throw new IllegalStateException(ex);
   1.199 +        }
   1.200 +    }
   1.201 +
   1.202 +    static final class Resource {
   1.203 +
   1.204 +        final InputStream httpContent;
   1.205 +        final String httpType;
   1.206 +        final String httpPath;
   1.207 +        final String[] parameters;
   1.208 +
   1.209 +        Resource(InputStream httpContent, String httpType, String httpPath,
   1.210 +            String[] parameters) {
   1.211 +            httpContent.mark(Integer.MAX_VALUE);
   1.212 +            this.httpContent = httpContent;
   1.213 +            this.httpType = httpType;
   1.214 +            this.httpPath = httpPath;
   1.215 +            this.parameters = parameters;
   1.216 +        }
   1.217 +    }
   1.218 +
   1.219 +    static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   1.220 +        for (;;) {
   1.221 +            int ch = is.read();
   1.222 +            if (ch == -1) {
   1.223 +                break;
   1.224 +            }
   1.225 +            if (ch == '$' && params.length > 0) {
   1.226 +                int cnt = is.read() - '0';
   1.227 +                if (baseURL != null && cnt == 'U' - '0') {
   1.228 +                    os.write(baseURL.getBytes("UTF-8"));
   1.229 +                } else {
   1.230 +                    if (cnt >= 0 && cnt < params.length) {
   1.231 +                        os.write(params[cnt].getBytes("UTF-8"));
   1.232 +                    } else {
   1.233 +                        os.write('$');
   1.234 +                        os.write(cnt + '0');
   1.235 +                    }
   1.236 +                }
   1.237 +            } else {
   1.238 +                os.write(ch);
   1.239 +            }
   1.240 +        }
   1.241 +    }
   1.242 +
   1.243 +    private static class WS extends WebSocketApplication {
   1.244 +        private final Resource r;
   1.245 +
   1.246 +        private WS(Resource r) {
   1.247 +            this.r = r;
   1.248 +        }
   1.249 +
   1.250 +        @Override
   1.251 +        public void onMessage(WebSocket socket, String text) {
   1.252 +            try {
   1.253 +                r.httpContent.reset();
   1.254 +                ByteArrayOutputStream out = new ByteArrayOutputStream();
   1.255 +                copyStream(r.httpContent, out, null, text);
   1.256 +                String s = new String(out.toByteArray(), "UTF-8");
   1.257 +                socket.send(s);
   1.258 +            } catch (IOException ex) {
   1.259 +                LOG.log(Level.WARNING, null, ex);
   1.260 +            }
   1.261 +        }
   1.262 +        private static final Logger LOG = Logger.getLogger(WS.class.getName());
   1.263 +
   1.264 +    }
   1.265 +}