Using profiles. Twitter demo can execute and test properly in FX profile now
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.UnsupportedEncodingException;
27 import java.io.Writer;
29 import java.net.URISyntaxException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Enumeration;
34 import java.util.LinkedHashSet;
35 import java.util.List;
37 import java.util.concurrent.BlockingQueue;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.LinkedBlockingQueue;
40 import java.util.concurrent.TimeUnit;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
43 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
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;
51 import org.glassfish.grizzly.http.util.HttpStatus;
54 * Lightweight server to launch Bck2Brwsr applications and tests.
55 * Supports execution in native browser as well as Java's internal
58 abstract class BaseHTTPLauncher extends Launcher implements Closeable {
59 private static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
60 private static final InvocationContext END = new InvocationContext(null, null, null);
61 private final Set<ClassLoader> loaders = new LinkedHashSet<>();
62 private final BlockingQueue<InvocationContext> 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 BaseHTTPLauncher(String cmd) {
72 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
77 InvocationContext runMethod(InvocationContext c) throws IOException {
78 loaders.add(c.clazz.getClassLoader());
82 } catch (InterruptedException ex) {
83 throw new IOException(ex);
88 public void setTimeout(long ms) {
92 public void addClassLoader(ClassLoader url) {
93 this.loaders.add(url);
96 ClassLoader[] loaders() {
97 return loaders.toArray(new ClassLoader[loaders.size()]);
100 public void showURL(String startpage) throws IOException {
101 if (!startpage.startsWith("/")) {
102 startpage = "/" + startpage;
104 HttpServer s = initServer(".", true);
105 int last = startpage.lastIndexOf('/');
106 String prefix = startpage.substring(0, last);
107 String simpleName = startpage.substring(last);
108 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
110 launchServerAndBrwsr(s, simpleName);
111 } catch (URISyntaxException | InterruptedException ex) {
112 throw new IOException(ex);
116 void showDirectory(File dir, String startpage) throws IOException {
117 if (!startpage.startsWith("/")) {
118 startpage = "/" + startpage;
120 HttpServer s = initServer(dir.getPath(), false);
122 launchServerAndBrwsr(s, startpage);
123 } catch (URISyntaxException | InterruptedException ex) {
124 throw new IOException(ex);
129 public void initialize() throws IOException {
132 } catch (InterruptedException ex) {
133 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
136 } catch (Exception ex) {
137 if (ex instanceof IOException) {
138 throw (IOException)ex;
140 if (ex instanceof RuntimeException) {
141 throw (RuntimeException)ex;
143 throw new IOException(ex);
147 private HttpServer initServer(String path, boolean addClasses) throws IOException {
148 HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
150 final ServerConfiguration conf = s.getServerConfiguration();
152 conf.addHttpHandler(new VM(), "/bck2brwsr.js");
153 conf.addHttpHandler(new Classes(resources), "/classes/");
158 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
159 wait = new CountDownLatch(1);
160 server = initServer(".", true);
161 final ServerConfiguration conf = server.getServerConfiguration();
163 class DynamicResourceHandler extends HttpHandler {
164 private final InvocationContext ic;
165 public DynamicResourceHandler(InvocationContext ic) {
166 if (ic == null || ic.resources.isEmpty()) {
167 throw new NullPointerException();
170 for (Resource r : ic.resources) {
171 conf.addHttpHandler(this, r.httpPath);
175 public void close() {
176 conf.removeHttpHandler(this);
180 public void service(Request request, Response response) throws Exception {
181 for (Resource r : ic.resources) {
182 if (r.httpPath.equals(request.getRequestURI())) {
183 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
184 response.setContentType(r.httpType);
185 r.httpContent.reset();
186 String[] params = null;
187 if (r.parameters.length != 0) {
188 params = new String[r.parameters.length];
189 for (int i = 0; i < r.parameters.length; i++) {
190 params[i] = request.getParameter(r.parameters[i]);
194 copyStream(r.httpContent, response.getOutputStream(), null, params);
200 conf.addHttpHandler(new Page(resources,
201 "org/apidesign/bck2brwsr/launcher/fximpl/harness.xhtml"
204 conf.addHttpHandler(new HttpHandler() {
206 List<InvocationContext> cases = new ArrayList<>();
207 DynamicResourceHandler prev;
209 public void service(Request request, Response response) throws Exception {
210 String id = request.getParameter("request");
211 String value = request.getParameter("result");
212 if (value != null && value.indexOf((char)0xC5) != -1) {
213 value = toUTF8(value);
217 InvocationContext mi = null;
220 if (id != null && value != null) {
221 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
222 value = decodeURL(value);
223 int indx = Integer.parseInt(id);
224 cases.get(indx).result(value, null);
225 if (++indx < cases.size()) {
226 mi = cases.get(indx);
227 LOG.log(Level.INFO, "Re-executing case {0}", indx);
231 if (!cases.isEmpty()) {
232 LOG.info("Re-executing test cases");
248 response.getWriter().write("");
251 LOG.log(Level.INFO, "End of data reached. Exiting.");
255 if (!mi.resources.isEmpty()) {
256 prev = new DynamicResourceHandler(mi);
260 final String cn = mi.clazz.getName();
261 final String mn = mi.methodName;
262 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
263 response.getWriter().write("{"
264 + "className: '" + cn + "', "
265 + "methodName: '" + mn + "', "
266 + "request: " + caseNmbr
268 if (mi.html != null) {
269 response.getWriter().write(", html: '");
270 response.getWriter().write(encodeJSON(mi.html));
271 response.getWriter().write("'");
273 response.getWriter().write("}");
277 this.brwsr = launchServerAndBrwsr(server, "/execute");
280 private static String encodeJSON(String in) {
281 StringBuilder sb = new StringBuilder();
282 for (int i = 0; i < in.length(); i++) {
283 char ch = in.charAt(i);
284 if (ch < 32 || ch == '\'' || ch == '"') {
286 String hs = "0000" + Integer.toHexString(ch);
287 hs = hs.substring(hs.length() - 4);
293 return sb.toString();
297 public void shutdown() throws IOException {
300 int prev = methods.size();
302 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
305 } catch (InterruptedException ex) {
306 throw new IOException(ex);
308 if (prev == methods.size()) {
311 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
317 "Timeout, but tests got from {0} to {1}. Trying again.",
318 new Object[]{prev, methods.size()}
321 stopServerAndBrwsr(server, brwsr);
324 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
330 if (ch == '$' && params.length > 0) {
331 int cnt = is.read() - '0';
332 if (baseURL != null && cnt == 'U' - '0') {
333 os.write(baseURL.getBytes("UTF-8"));
335 if (cnt >= 0 && cnt < params.length) {
336 os.write(params[cnt].getBytes("UTF-8"));
348 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
350 NetworkListener listener = server.getListeners().iterator().next();
351 int port = listener.getPort();
353 URI uri = new URI("http://localhost:" + port + page);
354 return showBrwsr(uri);
356 private static String toUTF8(String value) throws UnsupportedEncodingException {
357 byte[] arr = new byte[value.length()];
358 for (int i = 0; i < arr.length; i++) {
359 arr[i] = (byte)value.charAt(i);
361 return new String(arr, "UTF-8");
364 private static String decodeURL(String s) {
366 int pos = s.indexOf('%');
370 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
371 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
375 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
379 Process process = (Process)brwsr[0];
382 InputStream stdout = process.getInputStream();
383 InputStream stderr = process.getErrorStream();
384 drain("StdOut", stdout);
385 drain("StdErr", stderr);
389 res = process.waitFor();
390 } catch (InterruptedException ex) {
391 throw new IOException(ex);
393 LOG.log(Level.INFO, "Exit code: {0}", res);
395 deleteTree((File)brwsr[1]);
398 private static void drain(String name, InputStream is) throws IOException {
399 int av = is.available();
401 StringBuilder sb = new StringBuilder();
402 sb.append("v== ").append(name).append(" ==v\n");
404 sb.append((char)is.read());
406 sb.append("\n^== ").append(name).append(" ==^");
407 LOG.log(Level.INFO, sb.toString());
411 private void deleteTree(File file) {
415 File[] arr = file.listFiles();
425 public void close() throws IOException {
429 protected Object[] showBrwsr(URI uri) throws IOException {
430 LOG.log(Level.INFO, "Showing {0}", uri);
433 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
434 System.getProperty("java.vm.name"),
435 System.getProperty("java.vm.vendor"),
436 System.getProperty("java.vm.version"),
438 java.awt.Desktop.getDesktop().browse(uri);
439 LOG.log(Level.INFO, "Desktop.browse successfully finished");
441 } catch (UnsupportedOperationException ex) {
442 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
443 LOG.log(Level.FINE, null, ex);
447 String cmdName = cmd == null ? "xdg-open" : cmd;
449 cmdName, uri.toString()
451 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
452 final Process process = Runtime.getRuntime().exec(cmdArr);
453 return new Object[] { process, null };
457 abstract void generateBck2BrwsrJS(StringBuilder sb, Object loader) throws IOException;
460 public InputStream get(String resource) throws IOException {
461 for (ClassLoader l : loaders) {
463 Enumeration<URL> en = l.getResources(resource);
464 while (en.hasMoreElements()) {
465 u = en.nextElement();
468 return u.openStream();
471 throw new IOException("Can't find " + resource);
475 private static class Page extends HttpHandler {
476 final String resource;
477 private final String[] args;
478 private final Res res;
480 public Page(Res res, String resource, String... args) {
482 this.resource = resource;
483 this.args = args.length == 0 ? new String[] { "$0" } : args;
487 public void service(Request request, Response response) throws Exception {
488 String r = computePage(request);
489 if (r.startsWith("/")) {
492 String[] replace = {};
493 if (r.endsWith(".html")) {
494 response.setContentType("text/html");
495 LOG.info("Content type text/html");
498 if (r.endsWith(".xhtml")) {
499 response.setContentType("application/xhtml+xml");
500 LOG.info("Content type application/xhtml+xml");
503 OutputStream os = response.getOutputStream();
504 try (InputStream is = res.get(r)) {
505 copyStream(is, os, request.getRequestURL().toString(), replace);
506 } catch (IOException ex) {
507 response.setDetailMessage(ex.getLocalizedMessage());
509 response.setStatus(404);
513 protected String computePage(Request request) {
516 r = request.getHttpHandlerPath();
522 private static class SubTree extends Page {
524 public SubTree(Res res, String resource, String... args) {
525 super(res, resource, args);
529 protected String computePage(Request request) {
530 return resource + request.getHttpHandlerPath();
536 private class VM extends HttpHandler {
538 public void service(Request request, Response response) throws Exception {
539 response.setCharacterEncoding("UTF-8");
540 response.setContentType("text/javascript");
541 StringBuilder sb = new StringBuilder();
542 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
543 response.getWriter().write(sb.toString());
547 private static class Classes extends HttpHandler {
548 private final Res loader;
550 public Classes(Res loader) {
551 this.loader = loader;
555 public void service(Request request, Response response) throws Exception {
556 String res = request.getHttpHandlerPath();
557 if (res.startsWith("/")) {
558 res = res.substring(1);
560 try (InputStream is = loader.get(res)) {
561 response.setContentType("text/javascript");
562 Writer w = response.getWriter();
564 for (int i = 0;; i++) {
578 w.append(Integer.toString(b));
581 } catch (IOException ex) {
582 response.setStatus(HttpStatus.NOT_FOUND_404);
584 response.setDetailMessage(ex.getMessage());