ko-fx/src/test/java/org/netbeans/html/kofx/DynamicHTTP.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 16 Dec 2013 16:59:43 +0100
branchnetbeans
changeset 362 92fb71afdc0e
parent 358 ko-fx/src/test/java/org/apidesign/html/kofx/DynamicHTTP.java@80702021b851
child 365 5c93ad8c7a15
permissions -rw-r--r--
Moving implementation classes into org.netbeans.html namespace
     1 /**
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
     5  *
     6  * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
     7  * Other names may be trademarks of their respective owners.
     8  *
     9  * The contents of this file are subject to the terms of either the GNU
    10  * General Public License Version 2 only ("GPL") or the Common
    11  * Development and Distribution License("CDDL") (collectively, the
    12  * "License"). You may not use this file except in compliance with the
    13  * License. You can obtain a copy of the License at
    14  * http://www.netbeans.org/cddl-gplv2.html
    15  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    16  * specific language governing permissions and limitations under the
    17  * License.  When distributing the software, include this License Header
    18  * Notice in each file and include the License file at
    19  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    20  * particular file as subject to the "Classpath" exception as provided
    21  * by Oracle in the GPL Version 2 section of the License file that
    22  * accompanied this code. If applicable, add the following below the
    23  * License Header, with the fields enclosed by brackets [] replaced by
    24  * your own identifying information:
    25  * "Portions Copyrighted [year] [name of copyright owner]"
    26  *
    27  * Contributor(s):
    28  *
    29  * The Original Software is NetBeans. The Initial Developer of the Original
    30  * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
    31  *
    32  * If you wish your version of this file to be governed by only the CDDL
    33  * or only the GPL Version 2, indicate your decision by adding
    34  * "[Contributor] elects to include this software in this distribution
    35  * under the [CDDL or GPL Version 2] license." If you do not indicate a
    36  * single choice of license, a recipient has the option to distribute
    37  * your version of this file under either the CDDL, the GPL Version 2 or
    38  * to extend the choice of license to its licensees as provided above.
    39  * However, if you add GPL Version 2 code and therefore, elected the GPL
    40  * Version 2 license, then the option applies only if the new code is
    41  * made subject to such option by the copyright holder.
    42  */
    43 package org.netbeans.html.kofx;
    44 
    45 import java.io.ByteArrayInputStream;
    46 import java.io.ByteArrayOutputStream;
    47 import java.io.IOException;
    48 import java.io.InputStream;
    49 import java.io.OutputStream;
    50 import java.io.Reader;
    51 import java.net.URI;
    52 import java.net.URISyntaxException;
    53 import java.util.ArrayList;
    54 import java.util.List;
    55 import java.util.logging.Level;
    56 import java.util.logging.Logger;
    57 import org.glassfish.grizzly.PortRange;
    58 import org.glassfish.grizzly.http.server.HttpHandler;
    59 import org.glassfish.grizzly.http.server.HttpServer;
    60 import org.glassfish.grizzly.http.server.NetworkListener;
    61 import org.glassfish.grizzly.http.server.Request;
    62 import org.glassfish.grizzly.http.server.Response;
    63 import org.glassfish.grizzly.http.server.ServerConfiguration;
    64 import org.glassfish.grizzly.websockets.WebSocket;
    65 import org.glassfish.grizzly.websockets.WebSocketAddOn;
    66 import org.glassfish.grizzly.websockets.WebSocketApplication;
    67 import org.glassfish.grizzly.websockets.WebSocketEngine;
    68 
    69 /**
    70  *
    71  * @author Jaroslav Tulach <jtulach@netbeans.org>
    72  */
    73 final class DynamicHTTP extends HttpHandler {
    74     private static final Logger LOG = Logger.getLogger(DynamicHTTP.class.getName());
    75     private static int resourcesCount;
    76     private static List<Resource> resources;
    77     private static ServerConfiguration conf;
    78     private static HttpServer server;
    79     
    80     private DynamicHTTP() {
    81     }
    82     
    83     static URI initServer() throws Exception {
    84         server = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
    85         final WebSocketAddOn addon = new WebSocketAddOn();
    86         for (NetworkListener listener : server.getListeners()) {
    87             listener.registerAddOn(addon);
    88         }        
    89         resources = new ArrayList<Resource>();
    90 
    91         conf = server.getServerConfiguration();
    92         final DynamicHTTP dh = new DynamicHTTP();
    93 
    94         conf.addHttpHandler(dh, "/");
    95         
    96         server.start();
    97 
    98         return pageURL("http", server, "/test.html");
    99     }
   100     
   101     @Override
   102     public void service(Request request, Response response) throws Exception {
   103         if ("/test.html".equals(request.getRequestURI())) {
   104             response.setContentType("text/html");
   105             final InputStream is = DynamicHTTP.class.getResourceAsStream("test.html");
   106             copyStream(is, response.getOutputStream(), null);
   107             return;
   108         }
   109         if ("/dynamic".equals(request.getRequestURI())) {
   110             String mimeType = request.getParameter("mimeType");
   111             List<String> params = new ArrayList<String>();
   112             boolean webSocket = false;
   113             for (int i = 0;; i++) {
   114                 String p = request.getParameter("param" + i);
   115                 if (p == null) {
   116                     break;
   117                 }
   118                 if ("protocol:ws".equals(p)) {
   119                     webSocket = true;
   120                     continue;
   121                 }
   122                 params.add(p);
   123             }
   124             final String cnt = request.getParameter("content");
   125             String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
   126             ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
   127             URI url;
   128             final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
   129             if (webSocket) {
   130                 url = registerWebSocket(res);
   131             } else {
   132                 url = registerResource(res);
   133             }
   134             response.getWriter().write(url.toString());
   135             response.getWriter().write("\n");
   136             return;
   137         }
   138 
   139         for (Resource r : resources) {
   140             if (r.httpPath.equals(request.getRequestURI())) {
   141                 response.setContentType(r.httpType);
   142                 r.httpContent.reset();
   143                 String[] params = null;
   144                 if (r.parameters.length != 0) {
   145                     params = new String[r.parameters.length];
   146                     for (int i = 0; i < r.parameters.length; i++) {
   147                         params[i] = request.getParameter(r.parameters[i]);
   148                         if (params[i] == null) {
   149                             if ("http.method".equals(r.parameters[i])) {
   150                                 params[i] = request.getMethod().toString();
   151                             } else if ("http.requestBody".equals(r.parameters[i])) {
   152                                 Reader rdr = request.getReader();
   153                                 StringBuilder sb = new StringBuilder();
   154                                 for (;;) {
   155                                     int ch = rdr.read();
   156                                     if (ch == -1) {
   157                                         break;
   158                                     }
   159                                     sb.append((char) ch);
   160                                 }
   161                                 params[i] = sb.toString();
   162                             }
   163                         }
   164                         if (params[i] == null) {
   165                             params[i] = "null";
   166                         }
   167                     }
   168                 }
   169 
   170                 copyStream(r.httpContent, response.getOutputStream(), null, params);
   171             }
   172         }
   173     }
   174     
   175     private URI registerWebSocket(Resource r) {
   176         WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
   177         return pageURL("ws", server, r.httpPath);
   178     }
   179 
   180     private URI registerResource(Resource r) {
   181         if (!resources.contains(r)) {
   182             resources.add(r);
   183             conf.addHttpHandler(this, r.httpPath);
   184         }
   185         return pageURL("http", server, r.httpPath);
   186     }
   187     
   188     private static URI pageURL(String proto, HttpServer server, final String page) {
   189         NetworkListener listener = server.getListeners().iterator().next();
   190         int port = listener.getPort();
   191         try {
   192             return new URI(proto + "://localhost:" + port + page);
   193         } catch (URISyntaxException ex) {
   194             throw new IllegalStateException(ex);
   195         }
   196     }
   197     
   198     static final class Resource {
   199 
   200         final InputStream httpContent;
   201         final String httpType;
   202         final String httpPath;
   203         final String[] parameters;
   204 
   205         Resource(InputStream httpContent, String httpType, String httpPath,
   206             String[] parameters) {
   207             httpContent.mark(Integer.MAX_VALUE);
   208             this.httpContent = httpContent;
   209             this.httpType = httpType;
   210             this.httpPath = httpPath;
   211             this.parameters = parameters;
   212         }
   213     }
   214 
   215     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   216         for (;;) {
   217             int ch = is.read();
   218             if (ch == -1) {
   219                 break;
   220             }
   221             if (ch == '$' && params.length > 0) {
   222                 int cnt = is.read() - '0';
   223                 if (baseURL != null && cnt == 'U' - '0') {
   224                     os.write(baseURL.getBytes("UTF-8"));
   225                 } else {
   226                     if (cnt >= 0 && cnt < params.length) {
   227                         os.write(params[cnt].getBytes("UTF-8"));
   228                     } else {
   229                         os.write('$');
   230                         os.write(cnt + '0');
   231                     }
   232                 }
   233             } else {
   234                 os.write(ch);
   235             }
   236         }
   237     }
   238     
   239     private static class WS extends WebSocketApplication {
   240         private final Resource r;
   241 
   242         private WS(Resource r) {
   243             this.r = r;
   244         }
   245 
   246         @Override
   247         public void onMessage(WebSocket socket, String text) {
   248             try {
   249                 r.httpContent.reset();
   250                 ByteArrayOutputStream out = new ByteArrayOutputStream();
   251                 copyStream(r.httpContent, out, null, text);
   252                 String s = new String(out.toByteArray(), "UTF-8");
   253                 socket.send(s);
   254             } catch (IOException ex) {
   255                 LOG.log(Level.WARNING, "Error processing message " + text, ex);
   256             }
   257         }
   258     }
   259 }