2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
6 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7 * Other names may be trademarks of their respective owners.
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]"
29 * The Original Software is NetBeans. The Initial Developer of the Original
30 * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
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.
43 package org.netbeans.html.kofx;
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;
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;
71 * @author Jaroslav Tulach <jtulach@netbeans.org>
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;
80 private DynamicHTTP() {
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);
89 resources = new ArrayList<Resource>();
91 conf = server.getServerConfiguration();
92 final DynamicHTTP dh = new DynamicHTTP();
94 conf.addHttpHandler(dh, "/");
98 return pageURL("http", server, "/test.html");
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);
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);
118 if ("protocol:ws".equals(p)) {
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"));
128 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
130 url = registerWebSocket(res);
132 url = registerResource(res);
134 response.getWriter().write(url.toString());
135 response.getWriter().write("\n");
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();
159 sb.append((char) ch);
161 params[i] = sb.toString();
164 if (params[i] == null) {
170 copyStream(r.httpContent, response.getOutputStream(), null, params);
175 private URI registerWebSocket(Resource r) {
176 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
177 return pageURL("ws", server, r.httpPath);
180 private URI registerResource(Resource r) {
181 if (!resources.contains(r)) {
183 conf.addHttpHandler(this, r.httpPath);
185 return pageURL("http", server, r.httpPath);
188 private static URI pageURL(String proto, HttpServer server, final String page) {
189 NetworkListener listener = server.getListeners().iterator().next();
190 int port = listener.getPort();
192 return new URI(proto + "://localhost:" + port + page);
193 } catch (URISyntaxException ex) {
194 throw new IllegalStateException(ex);
198 static final class Resource {
200 final InputStream httpContent;
201 final String httpType;
202 final String httpPath;
203 final String[] parameters;
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;
215 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
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"));
226 if (cnt >= 0 && cnt < params.length) {
227 os.write(params[cnt].getBytes("UTF-8"));
239 private static class WS extends WebSocketApplication {
240 private final Resource r;
242 private WS(Resource r) {
247 public void onMessage(WebSocket socket, String text) {
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");
254 } catch (IOException ex) {
255 LOG.log(Level.WARNING, "Error processing message " + text, ex);