2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 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.ByteArrayOutputStream;
22 import java.io.Closeable;
24 import java.io.Flushable;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InterruptedIOException;
28 import java.io.OutputStream;
29 import java.io.Reader;
30 import java.io.UnsupportedEncodingException;
31 import java.io.Writer;
32 import java.net.JarURLConnection;
34 import java.net.URISyntaxException;
36 import java.net.URLConnection;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Enumeration;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.LinkedHashSet;
43 import java.util.List;
45 import java.util.Properties;
47 import java.util.concurrent.BlockingQueue;
48 import java.util.concurrent.Callable;
49 import java.util.concurrent.CountDownLatch;
50 import java.util.concurrent.LinkedBlockingQueue;
51 import java.util.concurrent.TimeUnit;
52 import java.util.jar.Attributes;
53 import java.util.jar.Manifest;
54 import java.util.logging.ConsoleHandler;
55 import java.util.logging.Level;
56 import java.util.logging.Logger;
57 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
58 import org.glassfish.grizzly.PortRange;
59 import org.glassfish.grizzly.http.server.HttpHandler;
60 import org.glassfish.grizzly.http.server.HttpServer;
61 import org.glassfish.grizzly.http.server.NetworkListener;
62 import org.glassfish.grizzly.http.server.Request;
63 import org.glassfish.grizzly.http.server.Response;
64 import org.glassfish.grizzly.http.server.ServerConfiguration;
65 import org.glassfish.grizzly.http.server.StaticHttpHandler;
66 import org.glassfish.grizzly.http.util.Header;
67 import org.glassfish.grizzly.http.util.HttpStatus;
68 import org.glassfish.grizzly.websockets.WebSocket;
69 import org.glassfish.grizzly.websockets.WebSocketAddOn;
70 import org.glassfish.grizzly.websockets.WebSocketApplication;
71 import org.glassfish.grizzly.websockets.WebSocketEngine;
74 * Lightweight server to launch Bck2Brwsr applications and tests.
75 * Supports execution in native browser as well as Java's internal
78 abstract class BaseHTTPLauncher extends Launcher implements Flushable, Closeable, Callable<HttpServer> {
79 static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
80 private static final InvocationContext END = new InvocationContext(null, null, null);
81 private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
82 private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
84 private final Res resources = new Res();
85 private final String cmd;
86 private Object[] brwsr;
87 private HttpServer server;
88 private CountDownLatch wait;
89 private Thread flushing;
90 private String rootPage;
93 public BaseHTTPLauncher(String cmd) {
95 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
100 InvocationContext runMethod(InvocationContext c) throws IOException {
101 loaders.add(c.clazz.getClassLoader());
105 } catch (InterruptedException ex) {
106 throw new IOException(ex);
111 public void setTimeout(long ms) {
115 public void addClassLoader(ClassLoader url) {
116 this.loaders.add(url);
119 ClassLoader[] loaders() {
120 return loaders.toArray(new ClassLoader[loaders.size()]);
124 void rootPage(String startpage) {
125 this.rootPage = startpage;
129 public void showURL(String startpage) throws IOException {
130 if (!startpage.startsWith("/")) {
131 startpage = "/" + startpage;
133 HttpServer s = initServer(".", true, "", false);
134 int last = startpage.lastIndexOf('/');
135 String prefix = startpage.substring(0, last);
136 String simpleName = startpage.substring(last);
137 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
140 launchServerAndBrwsr(s, simpleName);
141 } catch (Exception ex) {
142 throw new IOException(ex);
146 void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
147 if (!startpage.startsWith("/")) {
148 startpage = "/" + startpage;
150 String prefix = null;
151 if (!new File(dir, "bck2brwsr.js").exists()) {
152 int last = startpage.lastIndexOf('/');
154 prefix = startpage.substring(0, last);
157 HttpServer s = initServer(dir.getPath(), addClasses, prefix, false);
159 launchServerAndBrwsr(s, startpage);
160 } catch (Exception ex) {
161 throw new IOException(ex);
166 public void initialize() throws IOException {
169 } catch (InterruptedException ex) {
170 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
173 } catch (Exception ex) {
174 if (ex instanceof IOException) {
175 throw (IOException)ex;
177 if (ex instanceof RuntimeException) {
178 throw (RuntimeException)ex;
180 throw new IOException(ex);
184 private HttpServer initServer(String path, boolean addClasses, String vmPrefix, boolean unitTests) throws IOException {
185 HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
187 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
188 setPoolName("Fx/Bck2 Brwsr").
191 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
192 setPoolName("Kernel Fx/Bck2").
195 for (NetworkListener nl : s.getListeners()) {
196 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
197 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
200 final ServerConfiguration conf = s.getServerConfiguration();
201 VMAndPages vm = new VMAndPages(unitTests);
202 conf.addHttpHandler(vm, "/");
203 if (vmPrefix != null) {
204 vm.registerVM(vmPrefix + "/bck2brwsr.js");
210 conf.addHttpHandler(new Classes(resources), "/classes/");
212 if (rootPage != null) {
213 int last = rootPage.lastIndexOf('/');
214 String prefix = rootPage.substring(0, last);
215 String page = rootPage.substring(last);
216 s.getServerConfiguration().addHttpHandler(new SubTree("/pages" + page, resources, prefix), "/pages/");
218 final WebSocketAddOn addon = new WebSocketAddOn();
219 for (NetworkListener listener : s.getListeners()) {
220 listener.registerAddOn(addon);
222 Logger l = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler");
223 l.setLevel(Level.FINE);
224 l.setUseParentHandlers(false);
225 ConsoleHandler ch = new ConsoleHandler();
226 ch.setLevel(Level.ALL);
231 private static int resourcesCount;
232 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
233 wait = new CountDownLatch(1);
234 server = initServer(".", true, "", true);
235 final ServerConfiguration conf = server.getServerConfiguration();
237 class DynamicResourceHandler extends HttpHandler {
238 private final InvocationContext ic;
239 DynamicResourceHandler delegate;
240 public DynamicResourceHandler(InvocationContext ic) {
242 for (Resource r : ic.resources) {
243 conf.addHttpHandler(this, r.httpPath);
247 public void close(DynamicResourceHandler del) {
248 conf.removeHttpHandler(this);
253 public void service(Request request, Response response) throws Exception {
254 if (delegate != null) {
255 delegate.service(request, response);
259 if ("/dynamic".equals(request.getRequestURI())) {
260 boolean webSocket = false;
261 String mimeType = request.getParameter("mimeType");
262 List<String> params = new ArrayList<String>();
263 for (int i = 0; ; i++) {
264 String p = request.getParameter("param" + i);
269 if ("protocol:ws".equals(p)) {
273 final String cnt = request.getParameter("content");
274 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
275 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
277 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
279 url = registerWebSocket(res);
281 url = registerResource(res);
283 response.setHeader(Header.CacheControl, "no-cache");
284 response.setHeader(Header.Pragma, "no-cache");
285 response.getWriter().write(url.toString());
286 response.getWriter().write("\n");
290 for (Resource r : ic.resources) {
291 if (r.httpPath.equals(request.getRequestURI())) {
292 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
293 response.setContentType(r.httpType);
294 response.setHeader(Header.CacheControl, "no-cache");
295 response.setHeader(Header.Pragma, "no-cache");
296 r.httpContent.reset();
297 String[] params = null;
298 if (r.parameters.length != 0) {
299 params = new String[r.parameters.length];
300 for (int i = 0; i < r.parameters.length; i++) {
301 params[i] = request.getParameter(r.parameters[i]);
302 if (params[i] == null) {
303 if ("http.method".equals(r.parameters[i])) {
304 params[i] = request.getMethod().toString();
305 } else if ("http.requestBody".equals(r.parameters[i])) {
306 Reader rdr = request.getReader();
307 StringBuilder sb = new StringBuilder();
315 params[i] = sb.toString();
316 } else if (r.parameters[i].startsWith("http.header.")) {
317 params[i] = request.getHeader(r.parameters[i].substring(12));
320 if (params[i] == null) {
326 copyStream(r.httpContent, response.getOutputStream(), null, params);
331 private URI registerWebSocket(Resource r) {
332 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
333 return pageURL("ws", server, r.httpPath);
336 private URI registerResource(Resource r) {
337 if (!ic.resources.contains(r)) {
339 conf.addHttpHandler(this, r.httpPath);
341 return pageURL("http", server, r.httpPath);
345 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
347 conf.addHttpHandler(new HttpHandler() {
349 List<InvocationContext> cases = new ArrayList<InvocationContext>();
350 DynamicResourceHandler prev;
352 public void service(Request request, Response response) throws Exception {
353 String id = request.getParameter("request");
354 String value = request.getParameter("result");
355 String timeText = request.getParameter("time");
356 if (value != null && value.indexOf((char)0xC5) != -1) {
357 value = toUTF8(value);
360 if (timeText != null) {
362 time = (int) Double.parseDouble(timeText);
363 } catch (NumberFormatException numberFormatException) {
370 InvocationContext mi = null;
373 if (id != null && value != null) {
374 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
375 value = decodeURL(value);
376 int indx = Integer.parseInt(id);
377 cases.get(indx).result(value, time, null);
378 if (++indx < cases.size()) {
379 mi = cases.get(indx);
380 LOG.log(Level.INFO, "Re-executing case {0}", indx);
384 if (!cases.isEmpty()) {
385 LOG.info("Re-executing test cases");
395 final Writer w = response.getWriter();
400 LOG.log(Level.INFO, "End of data reached. Exiting.");
403 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
408 conf.addHttpHandler(prev, "/dynamic");
411 final String cn = mi.clazz.getName();
412 final String mn = mi.methodName;
413 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
415 + "className: '" + cn + "', "
416 + "methodName: '" + mn + "', "
417 + "request: " + caseNmbr
419 if (mi.args != null) {
420 w.write(", args: [");
422 for (String a : mi.args) {
431 if (mi.html != null) {
432 w.write(", html: '");
433 w.write(encodeJSON(mi.html));
440 String page = "/execute";
441 if (rootPage != null) {
442 int last = rootPage.lastIndexOf('/');
443 page = "/pages" + rootPage.substring(last);
446 this.brwsr = launchServerAndBrwsr(server, page);
449 private static String encodeJSON(String in) {
450 StringBuilder sb = new StringBuilder();
451 for (int i = 0; i < in.length(); i++) {
452 char ch = in.charAt(i);
453 if (ch < 32 || ch == '\'' || ch == '"') {
455 String hs = "0000" + Integer.toHexString(ch);
456 hs = hs.substring(hs.length() - 4);
462 return sb.toString();
466 public void shutdown() throws IOException {
469 private void shutdown(int exitCode) throws IOException {
470 synchronized (this) {
471 this.exitCode = exitCode;
472 if (flushing != null) {
473 flushing.interrupt();
479 int prev = methods.size();
481 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
484 } catch (InterruptedException ex) {
485 throw new IOException(ex);
487 if (prev == methods.size()) {
490 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
496 "Timeout, but tests got from {0} to {1}. Trying again.",
497 new Object[]{prev, methods.size()}
500 stopServerAndBrwsr(server, brwsr);
503 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
509 if (ch == '$' && params.length > 0) {
510 int cnt = is.read() - '0';
511 if (baseURL != null && cnt == 'U' - '0') {
512 os.write(baseURL.getBytes("UTF-8"));
514 if (cnt >= 0 && cnt < params.length) {
515 os.write(params[cnt].getBytes("UTF-8"));
527 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
529 URI uri = pageURL("http", server, page);
530 return showBrwsr(uri);
532 private static String toUTF8(String value) throws UnsupportedEncodingException {
533 byte[] arr = new byte[value.length()];
534 for (int i = 0; i < arr.length; i++) {
535 arr[i] = (byte)value.charAt(i);
537 return new String(arr, "UTF-8");
540 private static String decodeURL(String s) {
542 int pos = s.indexOf('%');
546 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
547 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
551 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
555 Process process = (Process)brwsr[0];
558 InputStream stdout = process.getInputStream();
559 InputStream stderr = process.getErrorStream();
560 drain("StdOut", stdout);
561 drain("StdErr", stderr);
565 res = process.waitFor();
566 } catch (InterruptedException ex) {
567 throw new IOException(ex);
569 LOG.log(Level.INFO, "Exit code: {0}", res);
571 deleteTree((File)brwsr[1]);
574 private static void drain(String name, InputStream is) throws IOException {
575 int av = is.available();
577 StringBuilder sb = new StringBuilder();
578 sb.append("v== ").append(name).append(" ==v\n");
580 sb.append((char)is.read());
582 sb.append("\n^== ").append(name).append(" ==^");
583 LOG.log(Level.INFO, sb.toString());
587 private void deleteTree(File file) {
591 File[] arr = file.listFiles();
601 public HttpServer call() throws Exception {
606 public synchronized void flush() throws IOException {
607 flushing = Thread.currentThread();
608 while (flushing == Thread.currentThread()) {
611 } catch (InterruptedException ex) {
612 LOG.log(Level.FINE, null, ex);
616 throw new IOException("Browser closed with exit code " + exitCode);
621 public void close() throws IOException {
625 protected Object[] showBrwsr(URI uri) throws IOException {
626 LOG.log(Level.INFO, "Showing {0}", uri);
629 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
630 System.getProperty("java.vm.name"),
631 System.getProperty("java.vm.vendor"),
632 System.getProperty("java.vm.version"),
634 java.awt.Desktop.getDesktop().browse(uri);
635 LOG.log(Level.INFO, "Desktop.browse successfully finished");
637 } catch (UnsupportedOperationException ex) {
638 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
639 LOG.log(Level.FINE, null, ex);
640 } catch (IOException ex) {
641 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
642 LOG.log(Level.FINE, null, ex);
646 String cmdName = cmd == null ? "xdg-open" : cmd;
648 cmdName, uri.toString()
650 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
651 final Process process = Runtime.getRuntime().exec(cmdArr);
652 return new Object[] { process, null };
656 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader, String url, boolean unitTestMode) throws IOException;
657 abstract String harnessResource();
658 Object compileJar(URL jar, URL precompiled) throws IOException {
661 String compileFromClassPath(URL f, Res loader) throws IOException {
665 private static URI pageURL(String protocol, HttpServer server, final String page) {
666 NetworkListener listener = server.getListeners().iterator().next();
667 int port = listener.getPort();
669 return new URI(protocol + "://localhost:" + port + page);
670 } catch (URISyntaxException ex) {
671 throw new IllegalStateException(ex);
676 private final Set<URL> ignore = new HashSet<URL>();
678 Object compileJar(URL jarURL) throws IOException {
679 List<String[]> libraries = new ArrayList<String[]>();
680 Map<String,Object[]> osgiJars = new HashMap<String, Object[]>();
681 for (ClassLoader loader : loaders) {
682 Enumeration<URL> en = loader.getResources("META-INF/MANIFEST.MF");
683 while (en.hasMoreElements()) {
684 URL e = en.nextElement();
685 Manifest mf = new Manifest(e.openStream());
686 for (Map.Entry<String, Attributes> entrySet : mf.getEntries().entrySet()) {
687 String key = entrySet.getKey();
688 Attributes attr = entrySet.getValue();
690 final String a = attr.getValue("Bck2BrwsrArtifactId");
691 final String g = attr.getValue("Bck2BrwsrGroupId");
692 final String v = attr.getValue("Bck2BrwsrVersion");
693 final String d = attr.getValue("Bck2BrwsrDebug");
694 final String n = attr.getValue("Bck2BrwsrName");
696 if (g != null && a != null && v != null && "true".equals(d)) {
697 libraries.add(new String[] {
702 final Attributes main = mf.getMainAttributes();
703 String symbol = main.getValue("Bundle-SymbolicName");
705 if (symbol == null) {
706 symbol = main.getValue("OpenIDE-Module-Name");
707 version = main.getValue("OpenIDE-Module-SpecificationVersion");
709 version = main.getValue("Bundle-Version");
711 if (symbol != null) {
712 osgiJars.put(symbol, new Object[] { e, version });
716 URL precompiled = null;
717 for (ClassLoader loader : loaders) {
718 for (String[] lib : libraries) {
719 final String res = "META-INF/maven/" + lib[1] + "/" + lib[0] + "/pom.properties";
720 URL props = loader.getResource(res);
722 URLConnection c = props.openConnection();
723 Properties load = new Properties();
724 final InputStream is = c.getInputStream();
727 if (lib[2].equals(load.getProperty("version"))) {
728 if (c instanceof JarURLConnection) {
729 final URL definedInURL = ((JarURLConnection)c).getJarFileURL();
730 if (definedInURL.equals(jarURL)) {
731 precompiled = loader.getResource(lib[3]);
738 if (precompiled == null) {
739 for (ClassLoader loader : loaders) {
740 for (String[] lib : libraries) {
741 Object[] urlVersion = osgiJars.get(lib[4]);
742 String expectVersion = lib[2];
743 if (expectVersion.endsWith("-SNAPSHOT")) {
744 expectVersion = expectVersion.substring(0, expectVersion.length() - 9);
746 if (urlVersion != null && urlVersion[1].toString().startsWith(expectVersion)) {
747 URL manifest = (URL) urlVersion[0];
748 if (manifest.openConnection() instanceof JarURLConnection) {
749 JarURLConnection jarConn = (JarURLConnection) manifest.openConnection();
750 if (jarConn.getJarFileURL().equals(jarURL)) {
751 precompiled = loader.getResource(lib[3]);
758 Object ret = BaseHTTPLauncher.this.compileJar(jarURL, precompiled);
762 String compileFromClassPath(URL f) throws IOException {
763 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
765 public URL get(String resource, int skip) throws IOException {
766 if (!resource.endsWith(".class")) {
767 return getResource(resource, skip);
770 for (ClassLoader l : loaders) {
771 Enumeration<URL> en = l.getResources(resource);
772 while (en.hasMoreElements()) {
773 u = en.nextElement();
774 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
780 if (u.toExternalForm().contains("rt.jar")) {
781 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
786 throw new IOException("Can't find " + resource);
788 private URL getResource(String resource, int skip) throws IOException {
789 for (ClassLoader l : loaders) {
790 Enumeration<URL> en = l.getResources(resource);
791 while (en.hasMoreElements()) {
792 final URL now = en.nextElement();
793 if (now.toExternalForm().contains("sisu-inject-bean")) {
794 // certainly we don't want this resource, as that
795 // module is not compiled with target 1.6, currently
798 if (now.getProtocol().equals("jar")) {
799 JarURLConnection juc = (JarURLConnection) now.openConnection();
800 if (now.getFile().endsWith(".class") && ignore.contains(juc.getJarFileURL())) {
809 throw new IOException("Not found (anymore of) " + resource);
813 private static class Page extends HttpHandler {
814 final String resource;
815 private final String[] args;
816 private final Res res;
817 private final String ensureBck2Brwsr;
819 public Page(Res res, String resource, String... args) {
820 this(null, res, resource, args);
823 Page(String ensureBck2Brwsr, Res res, String resource, String... args) {
824 this.ensureBck2Brwsr = ensureBck2Brwsr;
826 this.resource = resource;
827 this.args = args.length == 0 ? new String[] { "$0" } : args;
831 public void service(Request request, Response response) throws Exception {
832 String r = computePage(request);
833 if (r.startsWith("/")) {
836 String[] replace = {};
837 if (r.endsWith(".html")) {
838 response.setContentType("text/html");
839 LOG.info("Content type text/html");
842 if (r.endsWith(".xhtml")) {
843 response.setContentType("application/xhtml+xml");
844 LOG.info("Content type application/xhtml+xml");
848 InputStream is = res.get(r, 0).openStream();
849 if (ensureBck2Brwsr != null && ensureBck2Brwsr.equals(request.getRequestURI())) {
850 ByteArrayOutputStream tmp = new ByteArrayOutputStream();
851 copyStream(is, tmp, request.getRequestURL().toString(), replace);
852 String pageText = tmp.toString("UTF-8");
853 if (!pageText.contains("bck2brwsr.js")) {
854 int last = pageText.toLowerCase().indexOf("</body>");
856 last = pageText.length();
858 pageText = pageText.substring(0, last) +
859 "\n<script src='/bck2brwsr.js'></script>\n\n" +
860 pageText.substring(last);
862 response.getWriter().write(pageText);
864 OutputStream os = response.getOutputStream();
865 copyStream(is, os, request.getRequestURL().toString(), replace);
867 } catch (IOException ex) {
868 response.setDetailMessage(ex.getLocalizedMessage());
870 response.setStatus(404);
874 protected String computePage(Request request) {
877 r = request.getHttpHandlerPath();
883 private static class SubTree extends Page {
885 public SubTree(Res res, String resource, String... args) {
886 super(res, resource, args);
888 public SubTree(String ensureBck2Brwsr, Res res, String resource, String... args) {
889 super(ensureBck2Brwsr, res, resource, args);
893 protected String computePage(Request request) {
894 return resource + request.getHttpHandlerPath();
900 private class VMAndPages extends StaticHttpHandler {
901 private final boolean unitTestMode;
902 private String vmResource;
904 public VMAndPages(boolean unitTestMode) {
905 super((String[]) null);
906 this.unitTestMode = unitTestMode;
910 public void service(Request request, Response response) throws Exception {
911 final String exit = request.getParameter("exit");
915 exitCode = Integer.parseInt(exit);
916 } catch (NumberFormatException ex) {
917 exitCode = "true".equals(exit) ? 0 : -1;
919 if (exitCode != -1) {
920 LOG.info("Exit request received. Shutting down!");
924 if (request.getRequestURI().equals(vmResource)) {
925 response.setCharacterEncoding("UTF-8");
926 response.setContentType("text/javascript");
927 StringBuilder sb = new StringBuilder();
928 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources, request.getRequestURL().toString(), unitTestMode);
929 response.getWriter().write(sb.toString());
931 super.service(request, response);
935 private void registerVM(String vmResource) {
936 this.vmResource = vmResource;
940 private static class Classes extends HttpHandler {
941 private final Res loader;
943 public Classes(Res loader) {
944 this.loader = loader;
948 public void service(Request request, Response response) throws Exception {
949 String res = request.getHttpHandlerPath();
950 if (res.startsWith("/")) {
951 res = res.substring(1);
953 String skip = request.getParameter("skip");
954 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
955 URL url = loader.get(res, skipCnt);
956 if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
957 response.setCharacterEncoding("UTF-8");
958 if (url.getProtocol().equals("jar")) {
959 JarURLConnection juc = (JarURLConnection) url.openConnection();
962 s = loader.compileJar(juc.getJarFileURL());
963 } catch (IOException iOException) {
964 throw new IOException("Can't compile " + url.toExternalForm(), iOException);
966 if (s instanceof String) {
967 Writer w = response.getWriter();
972 if (s instanceof InputStream) {
973 copyStream((InputStream) s, response.getOutputStream(), null);
977 if (url.getProtocol().equals("file")) {
978 final String filePart = url.getFile();
979 if (filePart.endsWith(res)) {
984 filePart.substring(0, filePart.length() - res.length())
987 String s = loader.compileFromClassPath(url);
989 Writer w = response.getWriter();
995 } catch (IOException ex) {
996 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
998 InputStream is = null;
1001 throw new IOException("Resource not found");
1003 is = url.openStream();
1004 response.setContentType("text/javascript");
1005 Writer w = response.getWriter();
1007 for (int i = 0;; i++) {
1021 w.append(Integer.toString(b));
1024 } catch (IOException ex) {
1025 response.setStatus(HttpStatus.NOT_FOUND_404);
1026 response.setError();
1027 response.setDetailMessage(ex.getMessage());
1036 private static class WS extends WebSocketApplication {
1038 private final Resource r;
1040 private WS(Resource r) {
1045 public void onMessage(WebSocket socket, String text) {
1047 r.httpContent.reset();
1048 ByteArrayOutputStream out = new ByteArrayOutputStream();
1049 copyStream(r.httpContent, out, null, text);
1050 String s = new String(out.toByteArray(), "UTF-8");
1052 } catch (IOException ex) {
1053 LOG.log(Level.WARNING, null, ex);