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;
92 public BaseHTTPLauncher(String cmd) {
94 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
99 InvocationContext runMethod(InvocationContext c) throws IOException {
100 loaders.add(c.clazz.getClassLoader());
104 } catch (InterruptedException ex) {
105 throw new IOException(ex);
110 public void setTimeout(long ms) {
114 public void addClassLoader(ClassLoader url) {
115 this.loaders.add(url);
118 ClassLoader[] loaders() {
119 return loaders.toArray(new ClassLoader[loaders.size()]);
123 void rootPage(String startpage) {
124 this.rootPage = startpage;
128 public void showURL(String startpage) throws IOException {
129 if (!startpage.startsWith("/")) {
130 startpage = "/" + startpage;
132 HttpServer s = initServer(".", true, "", false);
133 int last = startpage.lastIndexOf('/');
134 String prefix = startpage.substring(0, last);
135 String simpleName = startpage.substring(last);
136 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
139 launchServerAndBrwsr(s, simpleName);
140 } catch (Exception ex) {
141 throw new IOException(ex);
145 void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
146 if (!startpage.startsWith("/")) {
147 startpage = "/" + startpage;
149 String prefix = null;
150 if (!new File(dir, "bck2brwsr.js").exists()) {
151 int last = startpage.lastIndexOf('/');
153 prefix = startpage.substring(0, last);
156 HttpServer s = initServer(dir.getPath(), addClasses, prefix, false);
158 launchServerAndBrwsr(s, startpage);
159 } catch (Exception ex) {
160 throw new IOException(ex);
165 public void initialize() throws IOException {
168 } catch (InterruptedException ex) {
169 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
172 } catch (Exception ex) {
173 if (ex instanceof IOException) {
174 throw (IOException)ex;
176 if (ex instanceof RuntimeException) {
177 throw (RuntimeException)ex;
179 throw new IOException(ex);
183 private HttpServer initServer(String path, boolean addClasses, String vmPrefix, boolean unitTests) throws IOException {
184 HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
186 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
187 setPoolName("Fx/Bck2 Brwsr").
190 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
191 setPoolName("Kernel Fx/Bck2").
194 for (NetworkListener nl : s.getListeners()) {
195 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
196 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
199 final ServerConfiguration conf = s.getServerConfiguration();
200 VMAndPages vm = new VMAndPages(unitTests);
201 conf.addHttpHandler(vm, "/");
202 if (vmPrefix != null) {
203 vm.registerVM(vmPrefix + "/bck2brwsr.js");
209 conf.addHttpHandler(new Classes(resources), "/classes/");
211 if (rootPage != null) {
212 int last = rootPage.lastIndexOf('/');
213 String prefix = rootPage.substring(0, last);
214 String page = rootPage.substring(last);
215 s.getServerConfiguration().addHttpHandler(new SubTree("/pages" + page, resources, prefix), "/pages/");
217 final WebSocketAddOn addon = new WebSocketAddOn();
218 for (NetworkListener listener : s.getListeners()) {
219 listener.registerAddOn(addon);
221 Logger l = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler");
222 l.setLevel(Level.FINE);
223 l.setUseParentHandlers(false);
224 ConsoleHandler ch = new ConsoleHandler();
225 ch.setLevel(Level.ALL);
230 private static int resourcesCount;
231 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
232 wait = new CountDownLatch(1);
233 server = initServer(".", true, "", true);
234 final ServerConfiguration conf = server.getServerConfiguration();
236 class DynamicResourceHandler extends HttpHandler {
237 private final InvocationContext ic;
238 DynamicResourceHandler delegate;
239 public DynamicResourceHandler(InvocationContext ic) {
241 for (Resource r : ic.resources) {
242 conf.addHttpHandler(this, r.httpPath);
246 public void close(DynamicResourceHandler del) {
247 conf.removeHttpHandler(this);
252 public void service(Request request, Response response) throws Exception {
253 if (delegate != null) {
254 delegate.service(request, response);
258 if ("/dynamic".equals(request.getRequestURI())) {
259 boolean webSocket = false;
260 String mimeType = request.getParameter("mimeType");
261 List<String> params = new ArrayList<String>();
262 for (int i = 0; ; i++) {
263 String p = request.getParameter("param" + i);
268 if ("protocol:ws".equals(p)) {
272 final String cnt = request.getParameter("content");
273 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
274 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
276 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
278 url = registerWebSocket(res);
280 url = registerResource(res);
282 response.setHeader(Header.CacheControl, "no-cache");
283 response.setHeader(Header.Pragma, "no-cache");
284 response.getWriter().write(url.toString());
285 response.getWriter().write("\n");
289 for (Resource r : ic.resources) {
290 if (r.httpPath.equals(request.getRequestURI())) {
291 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
292 response.setContentType(r.httpType);
293 response.setHeader(Header.CacheControl, "no-cache");
294 response.setHeader(Header.Pragma, "no-cache");
295 r.httpContent.reset();
296 String[] params = null;
297 if (r.parameters.length != 0) {
298 params = new String[r.parameters.length];
299 for (int i = 0; i < r.parameters.length; i++) {
300 params[i] = request.getParameter(r.parameters[i]);
301 if (params[i] == null) {
302 if ("http.method".equals(r.parameters[i])) {
303 params[i] = request.getMethod().toString();
304 } else if ("http.requestBody".equals(r.parameters[i])) {
305 Reader rdr = request.getReader();
306 StringBuilder sb = new StringBuilder();
314 params[i] = sb.toString();
315 } else if (r.parameters[i].startsWith("http.header.")) {
316 params[i] = request.getHeader(r.parameters[i].substring(12));
319 if (params[i] == null) {
325 copyStream(r.httpContent, response.getOutputStream(), null, params);
330 private URI registerWebSocket(Resource r) {
331 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
332 return pageURL("ws", server, r.httpPath);
335 private URI registerResource(Resource r) {
336 if (!ic.resources.contains(r)) {
338 conf.addHttpHandler(this, r.httpPath);
340 return pageURL("http", server, r.httpPath);
344 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
346 conf.addHttpHandler(new HttpHandler() {
348 List<InvocationContext> cases = new ArrayList<InvocationContext>();
349 DynamicResourceHandler prev;
351 public void service(Request request, Response response) throws Exception {
352 String id = request.getParameter("request");
353 String value = request.getParameter("result");
354 String timeText = request.getParameter("time");
355 if (value != null && value.indexOf((char)0xC5) != -1) {
356 value = toUTF8(value);
359 if (timeText != null) {
361 time = (int) Double.parseDouble(timeText);
362 } catch (NumberFormatException numberFormatException) {
369 InvocationContext mi = null;
372 if (id != null && value != null) {
373 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
374 value = decodeURL(value);
375 int indx = Integer.parseInt(id);
376 cases.get(indx).result(value, time, null);
377 if (++indx < cases.size()) {
378 mi = cases.get(indx);
379 LOG.log(Level.INFO, "Re-executing case {0}", indx);
383 if (!cases.isEmpty()) {
384 LOG.info("Re-executing test cases");
394 final Writer w = response.getWriter();
399 LOG.log(Level.INFO, "End of data reached. Exiting.");
402 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
407 conf.addHttpHandler(prev, "/dynamic");
410 final String cn = mi.clazz.getName();
411 final String mn = mi.methodName;
412 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
414 + "className: '" + cn + "', "
415 + "methodName: '" + mn + "', "
416 + "request: " + caseNmbr
418 if (mi.args != null) {
419 w.write(", args: [");
421 for (String a : mi.args) {
430 if (mi.html != null) {
431 w.write(", html: '");
432 w.write(encodeJSON(mi.html));
439 String page = "/execute";
440 if (rootPage != null) {
441 int last = rootPage.lastIndexOf('/');
442 page = "/pages" + rootPage.substring(last);
445 this.brwsr = launchServerAndBrwsr(server, page);
448 private static String encodeJSON(String in) {
449 StringBuilder sb = new StringBuilder();
450 for (int i = 0; i < in.length(); i++) {
451 char ch = in.charAt(i);
452 if (ch < 32 || ch == '\'' || ch == '"') {
454 String hs = "0000" + Integer.toHexString(ch);
455 hs = hs.substring(hs.length() - 4);
461 return sb.toString();
465 public void shutdown() throws IOException {
466 synchronized (this) {
467 if (flushing != null) {
468 flushing.interrupt();
474 int prev = methods.size();
476 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
479 } catch (InterruptedException ex) {
480 throw new IOException(ex);
482 if (prev == methods.size()) {
485 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
491 "Timeout, but tests got from {0} to {1}. Trying again.",
492 new Object[]{prev, methods.size()}
495 stopServerAndBrwsr(server, brwsr);
498 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
504 if (ch == '$' && params.length > 0) {
505 int cnt = is.read() - '0';
506 if (baseURL != null && cnt == 'U' - '0') {
507 os.write(baseURL.getBytes("UTF-8"));
509 if (cnt >= 0 && cnt < params.length) {
510 os.write(params[cnt].getBytes("UTF-8"));
522 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
524 URI uri = pageURL("http", server, page);
525 return showBrwsr(uri);
527 private static String toUTF8(String value) throws UnsupportedEncodingException {
528 byte[] arr = new byte[value.length()];
529 for (int i = 0; i < arr.length; i++) {
530 arr[i] = (byte)value.charAt(i);
532 return new String(arr, "UTF-8");
535 private static String decodeURL(String s) {
537 int pos = s.indexOf('%');
541 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
542 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
546 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
550 Process process = (Process)brwsr[0];
553 InputStream stdout = process.getInputStream();
554 InputStream stderr = process.getErrorStream();
555 drain("StdOut", stdout);
556 drain("StdErr", stderr);
560 res = process.waitFor();
561 } catch (InterruptedException ex) {
562 throw new IOException(ex);
564 LOG.log(Level.INFO, "Exit code: {0}", res);
566 deleteTree((File)brwsr[1]);
569 private static void drain(String name, InputStream is) throws IOException {
570 int av = is.available();
572 StringBuilder sb = new StringBuilder();
573 sb.append("v== ").append(name).append(" ==v\n");
575 sb.append((char)is.read());
577 sb.append("\n^== ").append(name).append(" ==^");
578 LOG.log(Level.INFO, sb.toString());
582 private void deleteTree(File file) {
586 File[] arr = file.listFiles();
596 public HttpServer call() throws Exception {
601 public synchronized void flush() throws IOException {
602 flushing = Thread.currentThread();
603 while (flushing == Thread.currentThread()) {
606 } catch (InterruptedException ex) {
607 LOG.log(Level.FINE, null, ex);
613 public void close() throws IOException {
617 protected Object[] showBrwsr(URI uri) throws IOException {
618 LOG.log(Level.INFO, "Showing {0}", uri);
621 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
622 System.getProperty("java.vm.name"),
623 System.getProperty("java.vm.vendor"),
624 System.getProperty("java.vm.version"),
626 java.awt.Desktop.getDesktop().browse(uri);
627 LOG.log(Level.INFO, "Desktop.browse successfully finished");
629 } catch (UnsupportedOperationException ex) {
630 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
631 LOG.log(Level.FINE, null, ex);
632 } catch (IOException ex) {
633 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
634 LOG.log(Level.FINE, null, ex);
638 String cmdName = cmd == null ? "xdg-open" : cmd;
640 cmdName, uri.toString()
642 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
643 final Process process = Runtime.getRuntime().exec(cmdArr);
644 return new Object[] { process, null };
648 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader, String url, boolean unitTestMode) throws IOException;
649 abstract String harnessResource();
650 Object compileJar(URL jar, URL precompiled) throws IOException {
653 String compileFromClassPath(URL f, Res loader) throws IOException {
657 private static URI pageURL(String protocol, HttpServer server, final String page) {
658 NetworkListener listener = server.getListeners().iterator().next();
659 int port = listener.getPort();
661 return new URI(protocol + "://localhost:" + port + page);
662 } catch (URISyntaxException ex) {
663 throw new IllegalStateException(ex);
668 private final Set<URL> ignore = new HashSet<URL>();
670 Object compileJar(URL jarURL) throws IOException {
671 List<String[]> libraries = new ArrayList<String[]>();
672 Map<String,Object[]> osgiJars = new HashMap<String, Object[]>();
673 for (ClassLoader loader : loaders) {
674 Enumeration<URL> en = loader.getResources("META-INF/MANIFEST.MF");
675 while (en.hasMoreElements()) {
676 URL e = en.nextElement();
677 Manifest mf = new Manifest(e.openStream());
678 for (Map.Entry<String, Attributes> entrySet : mf.getEntries().entrySet()) {
679 String key = entrySet.getKey();
680 Attributes attr = entrySet.getValue();
682 final String a = attr.getValue("Bck2BrwsrArtifactId");
683 final String g = attr.getValue("Bck2BrwsrGroupId");
684 final String v = attr.getValue("Bck2BrwsrVersion");
685 final String d = attr.getValue("Bck2BrwsrDebug");
686 final String n = attr.getValue("Bck2BrwsrName");
688 if (g != null && a != null && v != null && "true".equals(d)) {
689 libraries.add(new String[] {
694 final Attributes main = mf.getMainAttributes();
695 String symbol = main.getValue("Bundle-SymbolicName");
697 if (symbol == null) {
698 symbol = main.getValue("OpenIDE-Module-Name");
699 version = main.getValue("OpenIDE-Module-SpecificationVersion");
701 version = main.getValue("Bundle-Version");
703 if (symbol != null) {
704 osgiJars.put(symbol, new Object[] { e, version });
708 URL precompiled = null;
709 for (ClassLoader loader : loaders) {
710 for (String[] lib : libraries) {
711 final String res = "META-INF/maven/" + lib[1] + "/" + lib[0] + "/pom.properties";
712 URL props = loader.getResource(res);
714 URLConnection c = props.openConnection();
715 Properties load = new Properties();
716 final InputStream is = c.getInputStream();
719 if (lib[2].equals(load.getProperty("version"))) {
720 if (c instanceof JarURLConnection) {
721 final URL definedInURL = ((JarURLConnection)c).getJarFileURL();
722 if (definedInURL.equals(jarURL)) {
723 precompiled = loader.getResource(lib[3]);
730 if (precompiled == null) {
731 for (ClassLoader loader : loaders) {
732 for (String[] lib : libraries) {
733 Object[] urlVersion = osgiJars.get(lib[4]);
734 String expectVersion = lib[2];
735 if (expectVersion.endsWith("-SNAPSHOT")) {
736 expectVersion = expectVersion.substring(0, expectVersion.length() - 9);
738 if (urlVersion != null && urlVersion[1].toString().startsWith(expectVersion)) {
739 URL manifest = (URL) urlVersion[0];
740 if (manifest.openConnection() instanceof JarURLConnection) {
741 JarURLConnection jarConn = (JarURLConnection) manifest.openConnection();
742 if (jarConn.getJarFileURL().equals(jarURL)) {
743 precompiled = loader.getResource(lib[3]);
750 Object ret = BaseHTTPLauncher.this.compileJar(jarURL, precompiled);
754 String compileFromClassPath(URL f) throws IOException {
755 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
757 public URL get(String resource, int skip) throws IOException {
758 if (!resource.endsWith(".class")) {
759 return getResource(resource, skip);
762 for (ClassLoader l : loaders) {
763 Enumeration<URL> en = l.getResources(resource);
764 while (en.hasMoreElements()) {
765 u = en.nextElement();
766 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
772 if (u.toExternalForm().contains("rt.jar")) {
773 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
778 throw new IOException("Can't find " + resource);
780 private URL getResource(String resource, int skip) throws IOException {
781 for (ClassLoader l : loaders) {
782 Enumeration<URL> en = l.getResources(resource);
783 while (en.hasMoreElements()) {
784 final URL now = en.nextElement();
785 if (now.toExternalForm().contains("sisu-inject-bean")) {
786 // certainly we don't want this resource, as that
787 // module is not compiled with target 1.6, currently
790 if (now.getProtocol().equals("jar")) {
791 JarURLConnection juc = (JarURLConnection) now.openConnection();
792 if (now.getFile().endsWith(".class") && ignore.contains(juc.getJarFileURL())) {
801 throw new IOException("Not found (anymore of) " + resource);
805 private static class Page extends HttpHandler {
806 final String resource;
807 private final String[] args;
808 private final Res res;
809 private final String ensureBck2Brwsr;
811 public Page(Res res, String resource, String... args) {
812 this(null, res, resource, args);
815 Page(String ensureBck2Brwsr, Res res, String resource, String... args) {
816 this.ensureBck2Brwsr = ensureBck2Brwsr;
818 this.resource = resource;
819 this.args = args.length == 0 ? new String[] { "$0" } : args;
823 public void service(Request request, Response response) throws Exception {
824 String r = computePage(request);
825 if (r.startsWith("/")) {
828 String[] replace = {};
829 if (r.endsWith(".html")) {
830 response.setContentType("text/html");
831 LOG.info("Content type text/html");
834 if (r.endsWith(".xhtml")) {
835 response.setContentType("application/xhtml+xml");
836 LOG.info("Content type application/xhtml+xml");
840 InputStream is = res.get(r, 0).openStream();
841 if (ensureBck2Brwsr != null && ensureBck2Brwsr.equals(request.getRequestURI())) {
842 ByteArrayOutputStream tmp = new ByteArrayOutputStream();
843 copyStream(is, tmp, request.getRequestURL().toString(), replace);
844 String pageText = tmp.toString("UTF-8");
845 if (!pageText.contains("bck2brwsr.js")) {
846 int last = pageText.toLowerCase().indexOf("</body>");
848 last = pageText.length();
850 pageText = pageText.substring(0, last) +
851 "\n<script src='/bck2brwsr.js'></script>\n\n" +
852 pageText.substring(last);
854 response.getWriter().write(pageText);
856 OutputStream os = response.getOutputStream();
857 copyStream(is, os, request.getRequestURL().toString(), replace);
859 } catch (IOException ex) {
860 response.setDetailMessage(ex.getLocalizedMessage());
862 response.setStatus(404);
866 protected String computePage(Request request) {
869 r = request.getHttpHandlerPath();
875 private static class SubTree extends Page {
877 public SubTree(Res res, String resource, String... args) {
878 super(res, resource, args);
880 public SubTree(String ensureBck2Brwsr, Res res, String resource, String... args) {
881 super(ensureBck2Brwsr, res, resource, args);
885 protected String computePage(Request request) {
886 return resource + request.getHttpHandlerPath();
892 private class VMAndPages extends StaticHttpHandler {
893 private final boolean unitTestMode;
894 private String vmResource;
896 public VMAndPages(boolean unitTestMode) {
897 super((String[]) null);
898 this.unitTestMode = unitTestMode;
902 public void service(Request request, Response response) throws Exception {
903 if ("true".equals(request.getParameter("exit"))) {
904 LOG.info("Exit request received. Shutting down!");
907 if (request.getRequestURI().equals(vmResource)) {
908 response.setCharacterEncoding("UTF-8");
909 response.setContentType("text/javascript");
910 StringBuilder sb = new StringBuilder();
911 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources, request.getRequestURL().toString(), unitTestMode);
912 response.getWriter().write(sb.toString());
914 super.service(request, response);
918 private void registerVM(String vmResource) {
919 this.vmResource = vmResource;
923 private static class Classes extends HttpHandler {
924 private final Res loader;
926 public Classes(Res loader) {
927 this.loader = loader;
931 public void service(Request request, Response response) throws Exception {
932 String res = request.getHttpHandlerPath();
933 if (res.startsWith("/")) {
934 res = res.substring(1);
936 String skip = request.getParameter("skip");
937 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
938 URL url = loader.get(res, skipCnt);
939 if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
940 response.setCharacterEncoding("UTF-8");
941 if (url.getProtocol().equals("jar")) {
942 JarURLConnection juc = (JarURLConnection) url.openConnection();
945 s = loader.compileJar(juc.getJarFileURL());
946 } catch (IOException iOException) {
947 throw new IOException("Can't compile " + url.toExternalForm(), iOException);
949 if (s instanceof String) {
950 Writer w = response.getWriter();
955 if (s instanceof InputStream) {
956 copyStream((InputStream) s, response.getOutputStream(), null);
960 if (url.getProtocol().equals("file")) {
961 final String filePart = url.getFile();
962 if (filePart.endsWith(res)) {
967 filePart.substring(0, filePart.length() - res.length())
970 String s = loader.compileFromClassPath(url);
972 Writer w = response.getWriter();
978 } catch (IOException ex) {
979 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
981 InputStream is = null;
984 throw new IOException("Resource not found");
986 is = url.openStream();
987 response.setContentType("text/javascript");
988 Writer w = response.getWriter();
990 for (int i = 0;; i++) {
1004 w.append(Integer.toString(b));
1007 } catch (IOException ex) {
1008 response.setStatus(HttpStatus.NOT_FOUND_404);
1009 response.setError();
1010 response.setDetailMessage(ex.getMessage());
1019 private static class WS extends WebSocketApplication {
1021 private final Resource r;
1023 private WS(Resource r) {
1028 public void onMessage(WebSocket socket, String text) {
1030 r.httpContent.reset();
1031 ByteArrayOutputStream out = new ByteArrayOutputStream();
1032 copyStream(r.httpContent, out, null, text);
1033 String s = new String(out.toByteArray(), "UTF-8");
1035 } catch (IOException ex) {
1036 LOG.log(Level.WARNING, null, ex);