Bringing the most recent default branch (especially the @Property MVVC) to the dew code
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, null);
60 private Set<ClassLoader> loaders = new LinkedHashSet<>();
61 private Set<Bck2Brwsr.Resources> xRes = new LinkedHashSet<>();
62 private BlockingQueue<MethodInvocation> methods = new LinkedBlockingQueue<>();
64 private final Res resources = new Res();
65 private final String cmd;
66 private Object[] brwsr;
67 private HttpServer server;
68 private CountDownLatch wait;
70 public Bck2BrwsrLauncher(String cmd) {
75 MethodInvocation addMethod(Class<?> clazz, String method, String html) throws IOException {
76 loaders.add(clazz.getClassLoader());
77 MethodInvocation c = new MethodInvocation(clazz.getName(), method, html);
81 } catch (InterruptedException ex) {
82 throw new IOException(ex);
87 public void setTimeout(long ms) {
91 public void addClassLoader(ClassLoader url) {
92 this.loaders.add(url);
95 public void showURL(String startpage) throws IOException {
96 if (!startpage.startsWith("/")) {
97 startpage = "/" + startpage;
99 HttpServer s = initServer();
100 s.getServerConfiguration().addHttpHandler(new Page(resources, null), "/");
102 launchServerAndBrwsr(s, startpage);
103 } catch (URISyntaxException | InterruptedException ex) {
104 throw new IOException(ex);
108 public static void main(String... args) throws Exception {
109 Bck2BrwsrLauncher l = new Bck2BrwsrLauncher(null);
110 l.addClassLoader(Bck2BrwsrLauncher.class.getClassLoader());
111 HttpServer s = l.initServer();
112 final Dew dew = new Dew();
113 s.getServerConfiguration().addHttpHandler(dew, "/dew/");
115 l.launchServerAndBrwsr(s, "/dew/");
120 public void initialize() throws IOException {
123 } catch (InterruptedException ex) {
124 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
127 } catch (Exception ex) {
128 if (ex instanceof IOException) {
129 throw (IOException)ex;
131 if (ex instanceof RuntimeException) {
132 throw (RuntimeException)ex;
134 throw new IOException(ex);
138 private HttpServer initServer() {
139 HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
141 final ServerConfiguration conf = s.getServerConfiguration();
142 conf.addHttpHandler(new Page(resources,
143 "org/apidesign/bck2brwsr/launcher/console.xhtml",
144 "org.apidesign.bck2brwsr.launcher.Console", "welcome", "false"
146 conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
147 conf.addHttpHandler(new VMInit(), "/vm.js");
148 conf.addHttpHandler(new Classes(resources), "/classes/");
152 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
153 wait = new CountDownLatch(1);
154 server = initServer();
155 ServerConfiguration conf = server.getServerConfiguration();
156 conf.addHttpHandler(new Page(resources,
157 "org/apidesign/bck2brwsr/launcher/harness.xhtml"
159 conf.addHttpHandler(new HttpHandler() {
161 List<MethodInvocation> cases = new ArrayList<>();
163 public void service(Request request, Response response) throws Exception {
164 String id = request.getParameter("request");
165 String value = request.getParameter("result");
167 if (id != null && value != null) {
168 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
169 value = decodeURL(value);
170 cases.get(Integer.parseInt(id)).result(value, null);
173 MethodInvocation mi = methods.take();
175 response.getWriter().write("");
178 LOG.log(Level.INFO, "End of data reached. Exiting.");
183 final String cn = mi.className;
184 final String mn = mi.methodName;
185 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{cnt, cn, mn});
186 response.getWriter().write("{"
187 + "className: '" + cn + "', "
188 + "methodName: '" + mn + "', "
191 if (mi.html != null) {
192 response.getWriter().write(", html: '");
193 response.getWriter().write(encodeJSON(mi.html));
194 response.getWriter().write("'");
196 response.getWriter().write("}");
201 this.brwsr = launchServerAndBrwsr(server, "/execute");
204 private static String encodeJSON(String in) {
205 StringBuilder sb = new StringBuilder();
206 for (int i = 0; i < in.length(); i++) {
207 char ch = in.charAt(i);
208 if (ch < 32 || ch == '\'' || ch == '"') {
210 String hs = "0000" + Integer.toHexString(ch);
211 hs = hs.substring(hs.length() - 4);
217 return sb.toString();
221 public void shutdown() throws IOException {
224 int prev = methods.size();
226 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
229 } catch (InterruptedException ex) {
230 throw new IOException(ex);
232 if (prev == methods.size()) {
235 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
241 "Timeout, but tests got from {0} to {1}. Trying again.",
242 new Object[]{prev, methods.size()}
245 stopServerAndBrwsr(server, brwsr);
248 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
254 if (ch == '$' && params.length > 0) {
255 int cnt = is.read() - '0';
256 if (cnt == 'U' - '0') {
257 os.write(baseURL.getBytes());
259 if (cnt >= 0 && cnt < params.length) {
260 os.write(params[cnt].getBytes());
268 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
270 NetworkListener listener = server.getListeners().iterator().next();
271 int port = listener.getPort();
273 URI uri = new URI("http://localhost:" + port + page);
274 LOG.log(Level.INFO, "Showing {0}", uri);
277 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
278 System.getProperty("java.vm.name"),
279 System.getProperty("java.vm.vendor"),
280 System.getProperty("java.vm.version"),
282 java.awt.Desktop.getDesktop().browse(uri);
283 LOG.log(Level.INFO, "Desktop.browse successfully finished");
285 } catch (UnsupportedOperationException ex) {
286 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
287 LOG.log(Level.FINE, null, ex);
291 String cmdName = cmd == null ? "xdg-open" : cmd;
293 cmdName, uri.toString()
295 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
296 final Process process = Runtime.getRuntime().exec(cmdArr);
297 return new Object[] { process, null };
301 private static String decodeURL(String s) {
303 int pos = s.indexOf('%');
307 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
308 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
312 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
316 Process process = (Process)brwsr[0];
319 InputStream stdout = process.getInputStream();
320 InputStream stderr = process.getErrorStream();
321 drain("StdOut", stdout);
322 drain("StdErr", stderr);
326 res = process.waitFor();
327 } catch (InterruptedException ex) {
328 throw new IOException(ex);
330 LOG.log(Level.INFO, "Exit code: {0}", res);
332 deleteTree((File)brwsr[1]);
335 private static void drain(String name, InputStream is) throws IOException {
336 int av = is.available();
338 StringBuilder sb = new StringBuilder();
339 sb.append("v== ").append(name).append(" ==v\n");
341 sb.append((char)is.read());
343 sb.append("\n^== ").append(name).append(" ==^");
344 LOG.log(Level.INFO, sb.toString());
348 private void deleteTree(File file) {
352 File[] arr = file.listFiles();
362 public void close() throws IOException {
366 private class Res implements Bck2Brwsr.Resources {
368 public InputStream get(String resource) throws IOException {
369 for (ClassLoader l : loaders) {
371 Enumeration<URL> en = l.getResources(resource);
372 while (en.hasMoreElements()) {
373 u = en.nextElement();
376 return u.openStream();
379 for (Bck2Brwsr.Resources r : xRes) {
380 InputStream is = r.get(resource);
385 throw new IOException("Can't find " + resource);
389 private static class Page extends HttpHandler {
390 private final String resource;
391 private final String[] args;
392 private final Res res;
394 public Page(Res res, String resource, String... args) {
396 this.resource = resource;
397 this.args = args.length == 0 ? new String[] { "$0" } : args;
401 public void service(Request request, Response response) throws Exception {
404 r = request.getHttpHandlerPath();
405 if (r.startsWith("/")) {
409 String[] replace = {};
410 if (r.endsWith(".html")) {
411 response.setContentType("text/html");
412 LOG.info("Content type text/html");
415 if (r.endsWith(".xhtml")) {
416 response.setContentType("application/xhtml+xml");
417 LOG.info("Content type application/xhtml+xml");
420 OutputStream os = response.getOutputStream();
421 try (InputStream is = res.get(r)) {
422 copyStream(is, os, request.getRequestURL().toString(), replace);
423 } catch (IOException ex) {
424 response.setDetailMessage(ex.getLocalizedMessage());
426 response.setStatus(404);
431 private static class VM extends HttpHandler {
432 private final Res loader;
434 public VM(Res loader) {
435 this.loader = loader;
439 public void service(Request request, Response response) throws Exception {
440 response.setCharacterEncoding("UTF-8");
441 response.setContentType("text/javascript");
442 Bck2Brwsr.generate(response.getWriter(), loader);
445 private static class VMInit extends HttpHandler {
450 public void service(Request request, Response response) throws Exception {
451 response.setCharacterEncoding("UTF-8");
452 response.setContentType("text/javascript");
453 response.getWriter().append(
454 "function ldCls(res) {\n"
455 + " var request = new XMLHttpRequest();\n"
456 + " request.open('GET', '/classes/' + res, false);\n"
457 + " request.send();\n"
458 + " var arr = eval('(' + request.responseText + ')');\n"
461 + "var vm = new bck2brwsr(ldCls);\n");
465 private static class Classes extends HttpHandler {
466 private final Res loader;
468 public Classes(Res loader) {
469 this.loader = loader;
473 public void service(Request request, Response response) throws Exception {
474 String res = request.getHttpHandlerPath();
475 if (res.startsWith("/")) {
476 res = res.substring(1);
478 try (InputStream is = loader.get(res)) {
479 response.setContentType("text/javascript");
480 Writer w = response.getWriter();
482 for (int i = 0;; i++) {
496 w.append(Integer.toString(b));
499 } catch (IOException ex) {
501 response.setDetailMessage(ex.getMessage());