Web development server initial prototype.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.bck2brwsr.launcher;
20 import java.io.Closeable;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InterruptedIOException;
25 import java.io.OutputStream;
26 import java.io.Writer;
28 import java.net.URISyntaxException;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Enumeration;
33 import java.util.LinkedHashSet;
34 import java.util.List;
36 import java.util.concurrent.BlockingQueue;
37 import java.util.concurrent.CountDownLatch;
38 import java.util.concurrent.LinkedBlockingQueue;
39 import java.util.concurrent.TimeUnit;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
42 import org.apidesign.bck2brwsr.dew.Dew;
43 import org.apidesign.vm4brwsr.Bck2Brwsr;
44 import org.glassfish.grizzly.PortRange;
45 import org.glassfish.grizzly.http.server.HttpHandler;
46 import org.glassfish.grizzly.http.server.HttpServer;
47 import org.glassfish.grizzly.http.server.NetworkListener;
48 import org.glassfish.grizzly.http.server.Request;
49 import org.glassfish.grizzly.http.server.Response;
50 import org.glassfish.grizzly.http.server.ServerConfiguration;
53 * Lightweight server to launch Bck2Brwsr applications and tests.
54 * Supports execution in native browser as well as Java's internal
57 final class Bck2BrwsrLauncher extends Launcher implements Closeable {
58 private static final Logger LOG = Logger.getLogger(Bck2BrwsrLauncher.class.getName());
59 private static final MethodInvocation END = new MethodInvocation(null, null);
60 private Set<ClassLoader> loaders = new LinkedHashSet<>();
61 private BlockingQueue<MethodInvocation> methods = new LinkedBlockingQueue<>();
63 private final Res resources = new Res();
64 private final String cmd;
65 private Object[] brwsr;
66 private HttpServer server;
67 private CountDownLatch wait;
69 public Bck2BrwsrLauncher(String cmd) {
74 public MethodInvocation addMethod(Class<?> clazz, String method) throws IOException {
75 loaders.add(clazz.getClassLoader());
76 MethodInvocation c = new MethodInvocation(clazz.getName(), method);
80 } catch (InterruptedException ex) {
81 throw new IOException(ex);
86 public void setTimeout(long ms) {
90 public void addClassLoader(ClassLoader url) {
91 this.loaders.add(url);
94 public void showURL(String startpage) throws IOException {
95 if (!startpage.startsWith("/")) {
96 startpage = "/" + startpage;
98 HttpServer s = initServer();
99 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
101 launchServerAndBrwsr(s, startpage);
102 } catch (URISyntaxException | InterruptedException ex) {
103 throw new IOException(ex);
107 public static void main(String... args) throws Exception {
108 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher(null);
109 HttpServer s = l.initServer();
110 s.getServerConfiguration().addHttpHandler(new Dew(), "/dew/");
111 l.launchServerAndBrwsr(s, "/dew/");
116 public void initialize() throws IOException {
119 } catch (InterruptedException ex) {
120 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
123 } catch (Exception ex) {
124 if (ex instanceof IOException) {
125 throw (IOException)ex;
127 if (ex instanceof RuntimeException) {
128 throw (RuntimeException)ex;
130 throw new IOException(ex);
134 private HttpServer initServer() {
135 HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
137 final ServerConfiguration conf = s.getServerConfiguration();
138 conf.addHttpHandler(new Page(resources,
139 "org/apidesign/bck2brwsr/launcher/console.xhtml",
140 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
142 conf.addHttpHandler(new Dew(), "/dew/");
143 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
144 conf.addHttpHandler(new VMInit(), "/vm.js");
145 conf.addHttpHandler(new Classes(resources), "/classes/");
149 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
150 wait = new CountDownLatch(1);
151 server = initServer();
152 ServerConfiguration conf = server.getServerConfiguration();
153 conf.addHttpHandler(new Page(resources,
154 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
156 conf.addHttpHandler(new HttpHandler() {
158 List<MethodInvocation> cases = new ArrayList<>();
160 public void service(Request request, Response response) throws Exception {
161 String id = request.getParameter("request");
162 String value = request.getParameter("result");
164 if (id != null && value != null) {
165 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
166 value = decodeURL(value);
167 cases.get(Integer.parseInt(id)).result(value, null);
170 MethodInvocation mi = methods.take();
172 response.getWriter().write("");
175 LOG.log(Level.INFO, "End of data reached. Exiting.");
180 final String cn = mi.className;
181 final String mn = mi.methodName;
182 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
183 response.getWriter().write("{"
184 + "className: '" + cn + "', "
185 + "methodName: '" + mn + "', "
192 this.brwsr = launchServerAndBrwsr(server, "/execute");
196 public void shutdown() throws IOException {
199 int prev = methods.size();
201 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
204 } catch (InterruptedException ex) {
205 throw new IOException(ex);
207 if (prev == methods.size()) {
210 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
216 "Timeout, but tests got from {0} to {1}. Trying again.",
217 new Object[]{prev, methods.size()}
220 stopServerAndBrwsr(server, brwsr);
223 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
230 int cnt = is.read() - '0';
231 if (cnt == 'U' - '0') {
232 os.write(baseURL.getBytes());
234 if (cnt < params.length) {
235 os.write(params[cnt].getBytes());
243 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
245 NetworkListener listener = server.getListeners().iterator().next();
246 int port = listener.getPort();
248 URI uri = new URI("http://localhost:" + port + page);
249 LOG.log(Level.INFO, "Showing {0}", uri);
251 // Desktop.getDesktop().browse(uri);
253 // } catch (UnsupportedOperationException ex)
255 // File dir = File.createTempFile("chrome", ".dir");
259 // "google-chrome", "--user-data-dir=" + dir, "--app=" + uri.toString()
261 // LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmd));
262 // final Process process = Runtime.getRuntime().exec(cmd);
263 // return new Object[] { process, dir };
266 String cmdName = cmd == null ? "xdg-open" : cmd;
268 cmdName, uri.toString()
270 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
271 final Process process = Runtime.getRuntime().exec(cmdArr);
272 return new Object[] { process, null };
276 private static String decodeURL(String s) {
278 int pos = s.indexOf('%');
282 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
283 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
287 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
291 Process process = (Process)brwsr[0];
294 InputStream stdout = process.getInputStream();
295 InputStream stderr = process.getErrorStream();
296 drain("StdOut", stdout);
297 drain("StdErr", stderr);
301 res = process.waitFor();
302 } catch (InterruptedException ex) {
303 throw new IOException(ex);
305 LOG.log(Level.INFO, "Exit code: {0}", res);
307 deleteTree((File)brwsr[1]);
310 private static void drain(String name, InputStream is) throws IOException {
311 int av = is.available();
313 StringBuilder sb = new StringBuilder();
314 sb.append("v== ").append(name).append(" ==v\n");
316 sb.append((char)is.read());
318 sb.append("\n^== ").append(name).append(" ==^");
319 LOG.log(Level.INFO, sb.toString());
323 private void deleteTree(File file) {
327 File[] arr = file.listFiles();
337 public void close() throws IOException {
341 private class Res implements Bck2Brwsr.Resources {
343 public InputStream get(String resource) throws IOException {
344 for (ClassLoader l : loaders) {
346 Enumeration<URL> en = l.getResources(resource);
347 while (en.hasMoreElements()) {
348 u = en.nextElement();
351 return u.openStream();
354 throw new IOException("Can't find " + resource);
358 private static class Page extends HttpHandler {
359 private final String resource;
360 private final String[] args;
361 private final Res res;
363 public Page(Res res, String resource, String... args) {
365 this.resource = resource;
370 public void service(Request request, Response response) throws Exception {
373 r = request.getHttpHandlerPath();
374 if (r.startsWith("/")) {
378 if (r.endsWith(".html") || r.endsWith(".xhtml")) {
379 response.setContentType("text/html");
381 OutputStream os = response.getOutputStream();
382 try (InputStream is = res.get(r)) {
383 copyStream(is, os, request.getRequestURL().toString(), args);
384 } catch (IOException ex) {
385 response.setDetailMessage(ex.getLocalizedMessage());
387 response.setStatus(404);
392 private static class VM extends HttpHandler {
393 private final Res loader;
395 public VM(Res loader) {
396 this.loader = loader;
400 public void service(Request request, Response response) throws Exception {
401 response.setCharacterEncoding("UTF-8");
402 response.setContentType("text/javascript");
403 Bck2Brwsr.generate(response.getWriter(), loader);
406 private static class VMInit extends HttpHandler {
411 public void service(Request request, Response response) throws Exception {
412 response.setCharacterEncoding("UTF-8");
413 response.setContentType("text/javascript");
414 response.getWriter().append(
415 "function ldCls(res) {\n"
416 + " var request = new XMLHttpRequest();\n"
417 + " request.open('GET', '/classes/' + res, false);\n"
418 + " request.send();\n"
419 + " var arr = eval('(' + request.responseText + ')');\n"
422 + "var vm = new bck2brwsr(ldCls);\n");
426 private static class Classes extends HttpHandler {
427 private final Res loader;
429 public Classes(Res loader) {
430 this.loader = loader;
434 public void service(Request request, Response response) throws Exception {
435 String res = request.getHttpHandlerPath();
436 if (res.startsWith("/")) {
437 res = res.substring(1);
439 try (InputStream is = loader.get(res)) {
440 response.setContentType("text/javascript");
441 Writer w = response.getWriter();
443 for (int i = 0;; i++) {
457 w.append(Integer.toString(b));
460 } catch (IOException ex) {
462 response.setDetailMessage(ex.getMessage());