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