ko-osgi-test/src/test/java/org/netbeans/html/ko/osgi/test/DynamicHTTP.java
author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
Fri, 07 Feb 2014 07:44:34 +0100
changeset 551 7ca2253fa86d
parent 371 87bbddaa2db1
child 790 30f20d9c0986
permissions -rw-r--r--
Updating copyright headers to mention current year
jaroslav@148
     1
/**
jaroslav@358
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jaroslav@148
     3
 *
jaroslav@551
     4
 * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
jaroslav@148
     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@148
     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@551
    30
 * Software is Oracle. Portions Copyright 2013-2014 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@148
    42
 */
jaroslav@371
    43
package org.netbeans.html.ko.osgi.test;
jaroslav@148
    44
jaroslav@148
    45
import java.io.ByteArrayInputStream;
jaroslav@247
    46
import java.io.ByteArrayOutputStream;
jaroslav@148
    47
import java.io.IOException;
jaroslav@148
    48
import java.io.InputStream;
jaroslav@148
    49
import java.io.OutputStream;
jaroslav@148
    50
import java.io.Reader;
jaroslav@148
    51
import java.net.URI;
jaroslav@148
    52
import java.net.URISyntaxException;
jaroslav@148
    53
import java.util.ArrayList;
jaroslav@148
    54
import java.util.List;
jaroslav@318
    55
import java.util.logging.Level;
jaroslav@318
    56
import java.util.logging.Logger;
jaroslav@148
    57
import org.glassfish.grizzly.PortRange;
jaroslav@148
    58
import org.glassfish.grizzly.http.server.HttpHandler;
jaroslav@148
    59
import org.glassfish.grizzly.http.server.HttpServer;
jaroslav@148
    60
import org.glassfish.grizzly.http.server.NetworkListener;
jaroslav@148
    61
import org.glassfish.grizzly.http.server.Request;
jaroslav@148
    62
import org.glassfish.grizzly.http.server.Response;
jaroslav@148
    63
import org.glassfish.grizzly.http.server.ServerConfiguration;
jaroslav@247
    64
import org.glassfish.grizzly.websockets.WebSocket;
jaroslav@247
    65
import org.glassfish.grizzly.websockets.WebSocketAddOn;
jaroslav@247
    66
import org.glassfish.grizzly.websockets.WebSocketApplication;
jaroslav@247
    67
import org.glassfish.grizzly.websockets.WebSocketEngine;
jaroslav@148
    68
jaroslav@148
    69
/**
jaroslav@148
    70
 *
jaroslav@148
    71
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jaroslav@148
    72
 */
jaroslav@148
    73
final class DynamicHTTP extends HttpHandler {
jaroslav@318
    74
    private static final Logger LOG = Logger.getLogger(DynamicHTTP.class.getName());
jaroslav@148
    75
    private static int resourcesCount;
jaroslav@148
    76
    private static List<Resource> resources;
jaroslav@148
    77
    private static ServerConfiguration conf;
jaroslav@148
    78
    private static HttpServer server;
jaroslav@148
    79
    
jaroslav@148
    80
    private DynamicHTTP() {
jaroslav@148
    81
    }
jaroslav@148
    82
    
jaroslav@148
    83
    static URI initServer() throws Exception {
jaroslav@148
    84
        server = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
jaroslav@247
    85
        final WebSocketAddOn addon = new WebSocketAddOn();
jaroslav@247
    86
        for (NetworkListener listener : server.getListeners()) {
jaroslav@247
    87
            listener.registerAddOn(addon);
jaroslav@247
    88
        }        
jaroslav@148
    89
        resources = new ArrayList<Resource>();
jaroslav@148
    90
jaroslav@148
    91
        conf = server.getServerConfiguration();
jaroslav@148
    92
        final DynamicHTTP dh = new DynamicHTTP();
jaroslav@148
    93
jaroslav@148
    94
        conf.addHttpHandler(dh, "/");
jaroslav@148
    95
        
jaroslav@148
    96
        server.start();
jaroslav@148
    97
jaroslav@247
    98
        return pageURL("http", server, "/test.html");
jaroslav@148
    99
    }
jaroslav@148
   100
    
jaroslav@148
   101
    @Override
jaroslav@148
   102
    public void service(Request request, Response response) throws Exception {
jaroslav@148
   103
        if ("/test.html".equals(request.getRequestURI())) {
jaroslav@148
   104
            response.setContentType("text/html");
jaroslav@148
   105
            final InputStream is = DynamicHTTP.class.getResourceAsStream("test.html");
jaroslav@148
   106
            copyStream(is, response.getOutputStream(), null);
jaroslav@148
   107
            return;
jaroslav@148
   108
        }
jaroslav@148
   109
        if ("/dynamic".equals(request.getRequestURI())) {
jaroslav@148
   110
            String mimeType = request.getParameter("mimeType");
jaroslav@148
   111
            List<String> params = new ArrayList<String>();
jaroslav@247
   112
            boolean webSocket = false;
jaroslav@148
   113
            for (int i = 0;; i++) {
jaroslav@148
   114
                String p = request.getParameter("param" + i);
jaroslav@148
   115
                if (p == null) {
jaroslav@148
   116
                    break;
jaroslav@148
   117
                }
jaroslav@247
   118
                if ("protocol:ws".equals(p)) {
jaroslav@247
   119
                    webSocket = true;
jaroslav@247
   120
                    continue;
jaroslav@247
   121
                }
jaroslav@148
   122
                params.add(p);
jaroslav@148
   123
            }
jaroslav@148
   124
            final String cnt = request.getParameter("content");
jaroslav@148
   125
            String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
jaroslav@148
   126
            ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
jaroslav@247
   127
            URI url;
jaroslav@247
   128
            final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
jaroslav@247
   129
            if (webSocket) {
jaroslav@247
   130
                url = registerWebSocket(res);
jaroslav@247
   131
            } else {
jaroslav@247
   132
                url = registerResource(res);
jaroslav@247
   133
            }
jaroslav@148
   134
            response.getWriter().write(url.toString());
jaroslav@148
   135
            response.getWriter().write("\n");
jaroslav@148
   136
            return;
jaroslav@148
   137
        }
jaroslav@148
   138
jaroslav@148
   139
        for (Resource r : resources) {
jaroslav@148
   140
            if (r.httpPath.equals(request.getRequestURI())) {
jaroslav@148
   141
                response.setContentType(r.httpType);
jaroslav@148
   142
                r.httpContent.reset();
jaroslav@148
   143
                String[] params = null;
jaroslav@148
   144
                if (r.parameters.length != 0) {
jaroslav@148
   145
                    params = new String[r.parameters.length];
jaroslav@148
   146
                    for (int i = 0; i < r.parameters.length; i++) {
jaroslav@148
   147
                        params[i] = request.getParameter(r.parameters[i]);
jaroslav@148
   148
                        if (params[i] == null) {
jaroslav@148
   149
                            if ("http.method".equals(r.parameters[i])) {
jaroslav@148
   150
                                params[i] = request.getMethod().toString();
jaroslav@148
   151
                            } else if ("http.requestBody".equals(r.parameters[i])) {
jaroslav@148
   152
                                Reader rdr = request.getReader();
jaroslav@148
   153
                                StringBuilder sb = new StringBuilder();
jaroslav@148
   154
                                for (;;) {
jaroslav@148
   155
                                    int ch = rdr.read();
jaroslav@148
   156
                                    if (ch == -1) {
jaroslav@148
   157
                                        break;
jaroslav@148
   158
                                    }
jaroslav@148
   159
                                    sb.append((char) ch);
jaroslav@148
   160
                                }
jaroslav@148
   161
                                params[i] = sb.toString();
jaroslav@148
   162
                            }
jaroslav@148
   163
                        }
jaroslav@148
   164
                        if (params[i] == null) {
jaroslav@148
   165
                            params[i] = "null";
jaroslav@148
   166
                        }
jaroslav@148
   167
                    }
jaroslav@148
   168
                }
jaroslav@148
   169
jaroslav@148
   170
                copyStream(r.httpContent, response.getOutputStream(), null, params);
jaroslav@148
   171
            }
jaroslav@148
   172
        }
jaroslav@148
   173
    }
jaroslav@247
   174
    
jaroslav@247
   175
    private URI registerWebSocket(Resource r) {
jaroslav@247
   176
        WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
jaroslav@247
   177
        return pageURL("ws", server, r.httpPath);
jaroslav@247
   178
    }
jaroslav@148
   179
jaroslav@148
   180
    private URI registerResource(Resource r) {
jaroslav@148
   181
        if (!resources.contains(r)) {
jaroslav@148
   182
            resources.add(r);
jaroslav@148
   183
            conf.addHttpHandler(this, r.httpPath);
jaroslav@148
   184
        }
jaroslav@247
   185
        return pageURL("http", server, r.httpPath);
jaroslav@148
   186
    }
jaroslav@148
   187
    
jaroslav@247
   188
    private static URI pageURL(String proto, HttpServer server, final String page) {
jaroslav@148
   189
        NetworkListener listener = server.getListeners().iterator().next();
jaroslav@148
   190
        int port = listener.getPort();
jaroslav@148
   191
        try {
jaroslav@247
   192
            return new URI(proto + "://localhost:" + port + page);
jaroslav@148
   193
        } catch (URISyntaxException ex) {
jaroslav@148
   194
            throw new IllegalStateException(ex);
jaroslav@148
   195
        }
jaroslav@148
   196
    }
jaroslav@148
   197
    
jaroslav@148
   198
    static final class Resource {
jaroslav@148
   199
jaroslav@148
   200
        final InputStream httpContent;
jaroslav@148
   201
        final String httpType;
jaroslav@148
   202
        final String httpPath;
jaroslav@148
   203
        final String[] parameters;
jaroslav@148
   204
jaroslav@148
   205
        Resource(InputStream httpContent, String httpType, String httpPath,
jaroslav@148
   206
            String[] parameters) {
jaroslav@148
   207
            httpContent.mark(Integer.MAX_VALUE);
jaroslav@148
   208
            this.httpContent = httpContent;
jaroslav@148
   209
            this.httpType = httpType;
jaroslav@148
   210
            this.httpPath = httpPath;
jaroslav@148
   211
            this.parameters = parameters;
jaroslav@148
   212
        }
jaroslav@148
   213
    }
jaroslav@148
   214
jaroslav@148
   215
    static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
jaroslav@148
   216
        for (;;) {
jaroslav@148
   217
            int ch = is.read();
jaroslav@148
   218
            if (ch == -1) {
jaroslav@148
   219
                break;
jaroslav@148
   220
            }
jaroslav@148
   221
            if (ch == '$' && params.length > 0) {
jaroslav@148
   222
                int cnt = is.read() - '0';
jaroslav@148
   223
                if (baseURL != null && cnt == 'U' - '0') {
jaroslav@148
   224
                    os.write(baseURL.getBytes("UTF-8"));
jaroslav@148
   225
                } else {
jaroslav@148
   226
                    if (cnt >= 0 && cnt < params.length) {
jaroslav@148
   227
                        os.write(params[cnt].getBytes("UTF-8"));
jaroslav@148
   228
                    } else {
jaroslav@148
   229
                        os.write('$');
jaroslav@148
   230
                        os.write(cnt + '0');
jaroslav@148
   231
                    }
jaroslav@148
   232
                }
jaroslav@148
   233
            } else {
jaroslav@148
   234
                os.write(ch);
jaroslav@148
   235
            }
jaroslav@148
   236
        }
jaroslav@148
   237
    }
jaroslav@148
   238
    
jaroslav@247
   239
    private static class WS extends WebSocketApplication {
jaroslav@247
   240
        private final Resource r;
jaroslav@247
   241
jaroslav@247
   242
        private WS(Resource r) {
jaroslav@247
   243
            this.r = r;
jaroslav@247
   244
        }
jaroslav@247
   245
jaroslav@247
   246
        @Override
jaroslav@247
   247
        public void onMessage(WebSocket socket, String text) {
jaroslav@247
   248
            try {
jaroslav@247
   249
                r.httpContent.reset();
jaroslav@247
   250
                ByteArrayOutputStream out = new ByteArrayOutputStream();
jaroslav@247
   251
                copyStream(r.httpContent, out, null, text);
jaroslav@247
   252
                String s = new String(out.toByteArray(), "UTF-8");
jaroslav@247
   253
                socket.send(s);
jaroslav@247
   254
            } catch (IOException ex) {
jaroslav@318
   255
                LOG.log(Level.WARNING, "Error processing message " + text, ex);
jaroslav@247
   256
            }
jaroslav@247
   257
        }
jaroslav@247
   258
    }
jaroslav@148
   259
}