Old handlers are sometimes used even after remoteHttpHandler is called. Invalidate old handlers by forcing them to delegate to the latest one.
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.ByteArrayInputStream;
21 import java.io.Closeable;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.InterruptedIOException;
26 import java.io.OutputStream;
27 import java.io.Reader;
28 import java.io.UnsupportedEncodingException;
29 import java.io.Writer;
31 import java.net.URISyntaxException;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Enumeration;
36 import java.util.LinkedHashSet;
37 import java.util.List;
39 import java.util.concurrent.BlockingQueue;
40 import java.util.concurrent.Callable;
41 import java.util.concurrent.CountDownLatch;
42 import java.util.concurrent.LinkedBlockingQueue;
43 import java.util.concurrent.TimeUnit;
44 import java.util.logging.Level;
45 import java.util.logging.Logger;
46 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
47 import org.glassfish.grizzly.PortRange;
48 import org.glassfish.grizzly.http.server.HttpHandler;
49 import org.glassfish.grizzly.http.server.HttpServer;
50 import org.glassfish.grizzly.http.server.NetworkListener;
51 import org.glassfish.grizzly.http.server.Request;
52 import org.glassfish.grizzly.http.server.Response;
53 import org.glassfish.grizzly.http.server.ServerConfiguration;
54 import org.glassfish.grizzly.http.util.HttpStatus;
55 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
58 * Lightweight server to launch Bck2Brwsr applications and tests.
59 * Supports execution in native browser as well as Java's internal
62 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
63 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
64 private static final InvocationContext END = new InvocationContext(null, null, null);
65 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
66 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
68 private final Res resources = new Res();
69 private final String cmd;
70 private Object[] brwsr;
71 private HttpServer server;
72 private CountDownLatch wait;
74 public BaseHTTPLauncher(String cmd) {
76 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
81 InvocationContext runMethod(InvocationContext c) throws IOException {
82 loaders.add(c.clazz.getClassLoader());
86 } catch (InterruptedException ex) {
87 throw new IOException(ex);
92 public void setTimeout(long ms) {
96 public void addClassLoader(ClassLoader url) {
97 this.loaders.add(url);
100 ClassLoader[] loaders() {
101 return loaders.toArray(new ClassLoader[loaders.size()]);
104 public void showURL(String startpage) throws IOException {
105 if (!startpage.startsWith("/")) {
106 startpage = "/" + startpage;
108 HttpServer s = initServer(".", true);
109 int last = startpage.lastIndexOf('/');
110 String prefix = startpage.substring(0, last);
111 String simpleName = startpage.substring(last);
112 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
115 launchServerAndBrwsr(s, simpleName);
116 } catch (Exception ex) {
117 throw new IOException(ex);
121 void showDirectory(File dir, String startpage) throws IOException {
122 if (!startpage.startsWith("/")) {
123 startpage = "/" + startpage;
125 HttpServer s = initServer(dir.getPath(), false);
127 launchServerAndBrwsr(s, startpage);
128 } catch (Exception ex) {
129 throw new IOException(ex);
134 public void initialize() throws IOException {
137 } catch (InterruptedException ex) {
138 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
141 } catch (Exception ex) {
142 if (ex instanceof IOException) {
143 throw (IOException)ex;
145 if (ex instanceof RuntimeException) {
146 throw (RuntimeException)ex;
148 throw new IOException(ex);
152 private HttpServer initServer(String path, boolean addClasses) throws IOException {
153 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
155 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
156 setPoolName("Fx/Bck2 Brwsr").
159 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
160 setPoolName("Kernel Fx/Bck2").
163 for (NetworkListener nl : s.getListeners()) {
164 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
165 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
168 final ServerConfiguration conf = s.getServerConfiguration();
170 conf.addHttpHandler(new VM(), "/bck2brwsr.js");
171 conf.addHttpHandler(new Classes(resources), "/classes/");
176 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
177 wait = new CountDownLatch(1);
178 server = initServer(".", true);
179 final ServerConfiguration conf = server.getServerConfiguration();
181 class DynamicResourceHandler extends HttpHandler {
182 private final InvocationContext ic;
183 private int resourcesCount;
184 DynamicResourceHandler delegate;
185 public DynamicResourceHandler(InvocationContext ic) {
187 for (Resource r : ic.resources) {
188 conf.addHttpHandler(this, r.httpPath);
192 public void close(DynamicResourceHandler del) {
193 conf.removeHttpHandler(this);
198 public void service(Request request, Response response) throws Exception {
199 if (delegate != null) {
200 delegate.service(request, response);
204 if ("/dynamic".equals(request.getRequestURI())) {
205 String mimeType = request.getParameter("mimeType");
206 List<String> params = new ArrayList<String>();
207 for (int i = 0; ; i++) {
208 String p = request.getParameter("param" + i);
214 final String cnt = request.getParameter("content");
215 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
216 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
217 URI url = registerResource(new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()])));
218 response.getWriter().write(url.toString());
219 response.getWriter().write("\n");
223 for (Resource r : ic.resources) {
224 if (r.httpPath.equals(request.getRequestURI())) {
225 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
226 response.setContentType(r.httpType);
227 r.httpContent.reset();
228 String[] params = null;
229 if (r.parameters.length != 0) {
230 params = new String[r.parameters.length];
231 for (int i = 0; i < r.parameters.length; i++) {
232 params[i] = request.getParameter(r.parameters[i]);
233 if (params[i] == null) {
234 if ("http.method".equals(r.parameters[i])) {
235 params[i] = request.getMethod().toString();
236 } else if ("http.requestBody".equals(r.parameters[i])) {
237 Reader rdr = request.getReader();
238 StringBuilder sb = new StringBuilder();
246 params[i] = sb.toString();
249 if (params[i] == null) {
255 copyStream(r.httpContent, response.getOutputStream(), null, params);
260 private URI registerResource(Resource r) {
261 if (!ic.resources.contains(r)) {
263 conf.addHttpHandler(this, r.httpPath);
265 return pageURL(server, r.httpPath);
269 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
271 conf.addHttpHandler(new HttpHandler() {
273 List<InvocationContext> cases = new ArrayList<InvocationContext>();
274 DynamicResourceHandler prev;
276 public void service(Request request, Response response) throws Exception {
277 String id = request.getParameter("request");
278 String value = request.getParameter("result");
279 if (value != null && value.indexOf((char)0xC5) != -1) {
280 value = toUTF8(value);
284 InvocationContext mi = null;
287 if (id != null && value != null) {
288 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
289 value = decodeURL(value);
290 int indx = Integer.parseInt(id);
291 cases.get(indx).result(value, null);
292 if (++indx < cases.size()) {
293 mi = cases.get(indx);
294 LOG.log(Level.INFO, "Re-executing case {0}", indx);
298 if (!cases.isEmpty()) {
299 LOG.info("Re-executing test cases");
310 response.getWriter().write("");
313 LOG.log(Level.INFO, "End of data reached. Exiting.");
316 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
321 conf.addHttpHandler(prev, "/dynamic");
324 final String cn = mi.clazz.getName();
325 final String mn = mi.methodName;
326 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
327 response.getWriter().write("{"
328 + "className: '" + cn + "', "
329 + "methodName: '" + mn + "', "
330 + "request: " + caseNmbr
332 if (mi.html != null) {
333 response.getWriter().write(", html: '");
334 response.getWriter().write(encodeJSON(mi.html));
335 response.getWriter().write("'");
337 response.getWriter().write("}");
341 this.brwsr = launchServerAndBrwsr(server, "/execute");
344 private static String encodeJSON(String in) {
345 StringBuilder sb = new StringBuilder();
346 for (int i = 0; i < in.length(); i++) {
347 char ch = in.charAt(i);
348 if (ch < 32 || ch == '\'' || ch == '"') {
350 String hs = "0000" + Integer.toHexString(ch);
351 hs = hs.substring(hs.length() - 4);
357 return sb.toString();
361 public void shutdown() throws IOException {
364 int prev = methods.size();
366 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
369 } catch (InterruptedException ex) {
370 throw new IOException(ex);
372 if (prev == methods.size()) {
375 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
381 "Timeout, but tests got from {0} to {1}. Trying again.",
382 new Object[]{prev, methods.size()}
385 stopServerAndBrwsr(server, brwsr);
388 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
394 if (ch == '$' && params.length > 0) {
395 int cnt = is.read() - '0';
396 if (baseURL != null && cnt == 'U' - '0') {
397 os.write(baseURL.getBytes("UTF-8"));
399 if (cnt >= 0 && cnt < params.length) {
400 os.write(params[cnt].getBytes("UTF-8"));
412 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
414 URI uri = pageURL(server, page);
415 return showBrwsr(uri);
417 private static String toUTF8(String value) throws UnsupportedEncodingException {
418 byte[] arr = new byte[value.length()];
419 for (int i = 0; i < arr.length; i++) {
420 arr[i] = (byte)value.charAt(i);
422 return new String(arr, "UTF-8");
425 private static String decodeURL(String s) {
427 int pos = s.indexOf('%');
431 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
432 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
436 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
440 Process process = (Process)brwsr[0];
443 InputStream stdout = process.getInputStream();
444 InputStream stderr = process.getErrorStream();
445 drain("StdOut", stdout);
446 drain("StdErr", stderr);
450 res = process.waitFor();
451 } catch (InterruptedException ex) {
452 throw new IOException(ex);
454 LOG.log(Level.INFO, "Exit code: {0}", res);
456 deleteTree((File)brwsr[1]);
459 private static void drain(String name, InputStream is) throws IOException {
460 int av = is.available();
462 StringBuilder sb = new StringBuilder();
463 sb.append("v== ").append(name).append(" ==v\n");
465 sb.append((char)is.read());
467 sb.append("\n^== ").append(name).append(" ==^");
468 LOG.log(Level.INFO, sb.toString());
472 private void deleteTree(File file) {
476 File[] arr = file.listFiles();
486 public HttpServer call() throws Exception {
491 public void close() throws IOException {
495 protected Object[] showBrwsr(URI uri) throws IOException {
496 LOG.log(Level.INFO, "Showing {0}", uri);
499 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
500 System.getProperty("java.vm.name"),
501 System.getProperty("java.vm.vendor"),
502 System.getProperty("java.vm.version"),
504 java.awt.Desktop.getDesktop().browse(uri);
505 LOG.log(Level.INFO, "Desktop.browse successfully finished");
507 } catch (UnsupportedOperationException ex) {
508 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
509 LOG.log(Level.FINE, null, ex);
513 String cmdName = cmd == null ? "xdg-open" : cmd;
515 cmdName, uri.toString()
517 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
518 final Process process = Runtime.getRuntime().exec(cmdArr);
519 return new Object[] { process, null };
523 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
524 abstract String harnessResource();
526 private static URI pageURL(HttpServer server, final String page) {
527 NetworkListener listener = server.getListeners().iterator().next();
528 int port = listener.getPort();
530 return new URI("http://localhost:" + port + page);
531 } catch (URISyntaxException ex) {
532 throw new IllegalStateException(ex);
537 public InputStream get(String resource) throws IOException {
539 for (ClassLoader l : loaders) {
540 Enumeration<URL> en = l.getResources(resource);
541 while (en.hasMoreElements()) {
542 u = en.nextElement();
543 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
544 return u.openStream();
549 if (u.toExternalForm().contains("rt.jar")) {
550 LOG.log(Level.WARNING, "Fallback to bootclasspath for {0}", u);
552 return u.openStream();
554 throw new IOException("Can't find " + resource);
558 private static class Page extends HttpHandler {
559 final String resource;
560 private final String[] args;
561 private final Res res;
563 public Page(Res res, String resource, String... args) {
565 this.resource = resource;
566 this.args = args.length == 0 ? new String[] { "$0" } : args;
570 public void service(Request request, Response response) throws Exception {
571 String r = computePage(request);
572 if (r.startsWith("/")) {
575 String[] replace = {};
576 if (r.endsWith(".html")) {
577 response.setContentType("text/html");
578 LOG.info("Content type text/html");
581 if (r.endsWith(".xhtml")) {
582 response.setContentType("application/xhtml+xml");
583 LOG.info("Content type application/xhtml+xml");
586 OutputStream os = response.getOutputStream();
588 InputStream is = res.get(r);
589 copyStream(is, os, request.getRequestURL().toString(), replace);
590 } catch (IOException ex) {
591 response.setDetailMessage(ex.getLocalizedMessage());
593 response.setStatus(404);
597 protected String computePage(Request request) {
600 r = request.getHttpHandlerPath();
606 private static class SubTree extends Page {
608 public SubTree(Res res, String resource, String... args) {
609 super(res, resource, args);
613 protected String computePage(Request request) {
614 return resource + request.getHttpHandlerPath();
620 private class VM extends HttpHandler {
622 public void service(Request request, Response response) throws Exception {
623 response.setCharacterEncoding("UTF-8");
624 response.setContentType("text/javascript");
625 StringBuilder sb = new StringBuilder();
626 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
627 response.getWriter().write(sb.toString());
631 private static class Classes extends HttpHandler {
632 private final Res loader;
634 public Classes(Res loader) {
635 this.loader = loader;
639 public void service(Request request, Response response) throws Exception {
640 String res = request.getHttpHandlerPath();
641 if (res.startsWith("/")) {
642 res = res.substring(1);
644 InputStream is = null;
646 is = loader.get(res);
647 response.setContentType("text/javascript");
648 Writer w = response.getWriter();
650 for (int i = 0;; i++) {
664 w.append(Integer.toString(b));
667 } catch (IOException ex) {
668 response.setStatus(HttpStatus.NOT_FOUND_404);
670 response.setDetailMessage(ex.getMessage());