Include the unit test initialization script in generated bck2brwsr.js rather than embedding it in the harness.html page
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;
91 public BaseHTTPLauncher(String cmd) {
93 addClassLoader(BaseHTTPLauncher.class.getClassLoader());
98 InvocationContext runMethod(InvocationContext c) throws IOException {
99 loaders.add(c.clazz.getClassLoader());
103 } catch (InterruptedException ex) {
104 throw new IOException(ex);
109 public void setTimeout(long ms) {
113 public void addClassLoader(ClassLoader url) {
114 this.loaders.add(url);
117 ClassLoader[] loaders() {
118 return loaders.toArray(new ClassLoader[loaders.size()]);
121 public void showURL(String startpage) throws IOException {
122 if (!startpage.startsWith("/")) {
123 startpage = "/" + startpage;
125 HttpServer s = initServer(".", true, "", false);
126 int last = startpage.lastIndexOf('/');
127 String prefix = startpage.substring(0, last);
128 String simpleName = startpage.substring(last);
129 s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
132 launchServerAndBrwsr(s, simpleName);
133 } catch (Exception ex) {
134 throw new IOException(ex);
138 void showDirectory(File dir, String startpage, boolean addClasses) throws IOException {
139 if (!startpage.startsWith("/")) {
140 startpage = "/" + startpage;
142 String prefix = null;
143 if (!new File(dir, "bck2brwsr.js").exists()) {
144 int last = startpage.lastIndexOf('/');
146 prefix = startpage.substring(0, last);
149 HttpServer s = initServer(dir.getPath(), addClasses, prefix, false);
151 launchServerAndBrwsr(s, startpage);
152 } catch (Exception ex) {
153 throw new IOException(ex);
158 public void initialize() throws IOException {
161 } catch (InterruptedException ex) {
162 final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
165 } catch (Exception ex) {
166 if (ex instanceof IOException) {
167 throw (IOException)ex;
169 if (ex instanceof RuntimeException) {
170 throw (RuntimeException)ex;
172 throw new IOException(ex);
176 private HttpServer initServer(String path, boolean addClasses, String vmPrefix, boolean unitTests) throws IOException {
177 HttpServer s = HttpServer.createSimpleServer(null, new PortRange(8080, 65535));
179 ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
180 setPoolName("Fx/Bck2 Brwsr").
183 ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
184 setPoolName("Kernel Fx/Bck2").
187 for (NetworkListener nl : s.getListeners()) {
188 nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
189 nl.getTransport().setKernelThreadPoolConfig(oneKernel);
192 final ServerConfiguration conf = s.getServerConfiguration();
193 VMAndPages vm = new VMAndPages(unitTests);
194 conf.addHttpHandler(vm, "/");
195 if (vmPrefix != null) {
196 vm.registerVM(vmPrefix + "/bck2brwsr.js");
202 conf.addHttpHandler(new Classes(resources), "/classes/");
204 final WebSocketAddOn addon = new WebSocketAddOn();
205 for (NetworkListener listener : s.getListeners()) {
206 listener.registerAddOn(addon);
208 Logger l = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler");
209 l.setLevel(Level.FINE);
210 l.setUseParentHandlers(false);
211 ConsoleHandler ch = new ConsoleHandler();
212 ch.setLevel(Level.ALL);
217 private static int resourcesCount;
218 private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
219 wait = new CountDownLatch(1);
220 server = initServer(".", true, "", true);
221 final ServerConfiguration conf = server.getServerConfiguration();
223 class DynamicResourceHandler extends HttpHandler {
224 private final InvocationContext ic;
225 DynamicResourceHandler delegate;
226 public DynamicResourceHandler(InvocationContext ic) {
228 for (Resource r : ic.resources) {
229 conf.addHttpHandler(this, r.httpPath);
233 public void close(DynamicResourceHandler del) {
234 conf.removeHttpHandler(this);
239 public void service(Request request, Response response) throws Exception {
240 if (delegate != null) {
241 delegate.service(request, response);
245 if ("/dynamic".equals(request.getRequestURI())) {
246 boolean webSocket = false;
247 String mimeType = request.getParameter("mimeType");
248 List<String> params = new ArrayList<String>();
249 for (int i = 0; ; i++) {
250 String p = request.getParameter("param" + i);
255 if ("protocol:ws".equals(p)) {
259 final String cnt = request.getParameter("content");
260 String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
261 ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
263 final Resource res = new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()]));
265 url = registerWebSocket(res);
267 url = registerResource(res);
269 response.setHeader(Header.CacheControl, "no-cache");
270 response.setHeader(Header.Pragma, "no-cache");
271 response.getWriter().write(url.toString());
272 response.getWriter().write("\n");
276 for (Resource r : ic.resources) {
277 if (r.httpPath.equals(request.getRequestURI())) {
278 LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
279 response.setContentType(r.httpType);
280 response.setHeader(Header.CacheControl, "no-cache");
281 response.setHeader(Header.Pragma, "no-cache");
282 r.httpContent.reset();
283 String[] params = null;
284 if (r.parameters.length != 0) {
285 params = new String[r.parameters.length];
286 for (int i = 0; i < r.parameters.length; i++) {
287 params[i] = request.getParameter(r.parameters[i]);
288 if (params[i] == null) {
289 if ("http.method".equals(r.parameters[i])) {
290 params[i] = request.getMethod().toString();
291 } else if ("http.requestBody".equals(r.parameters[i])) {
292 Reader rdr = request.getReader();
293 StringBuilder sb = new StringBuilder();
301 params[i] = sb.toString();
302 } else if (r.parameters[i].startsWith("http.header.")) {
303 params[i] = request.getHeader(r.parameters[i].substring(12));
306 if (params[i] == null) {
312 copyStream(r.httpContent, response.getOutputStream(), null, params);
317 private URI registerWebSocket(Resource r) {
318 WebSocketEngine.getEngine().register("", r.httpPath, new WS(r));
319 return pageURL("ws", server, r.httpPath);
322 private URI registerResource(Resource r) {
323 if (!ic.resources.contains(r)) {
325 conf.addHttpHandler(this, r.httpPath);
327 return pageURL("http", server, r.httpPath);
331 conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
333 conf.addHttpHandler(new HttpHandler() {
335 List<InvocationContext> cases = new ArrayList<InvocationContext>();
336 DynamicResourceHandler prev;
338 public void service(Request request, Response response) throws Exception {
339 String id = request.getParameter("request");
340 String value = request.getParameter("result");
341 String timeText = request.getParameter("time");
342 if (value != null && value.indexOf((char)0xC5) != -1) {
343 value = toUTF8(value);
346 if (timeText != null) {
348 time = (int) Double.parseDouble(timeText);
349 } catch (NumberFormatException numberFormatException) {
356 InvocationContext mi = null;
359 if (id != null && value != null) {
360 LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
361 value = decodeURL(value);
362 int indx = Integer.parseInt(id);
363 cases.get(indx).result(value, time, null);
364 if (++indx < cases.size()) {
365 mi = cases.get(indx);
366 LOG.log(Level.INFO, "Re-executing case {0}", indx);
370 if (!cases.isEmpty()) {
371 LOG.info("Re-executing test cases");
381 final Writer w = response.getWriter();
386 LOG.log(Level.INFO, "End of data reached. Exiting.");
389 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
394 conf.addHttpHandler(prev, "/dynamic");
397 final String cn = mi.clazz.getName();
398 final String mn = mi.methodName;
399 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
401 + "className: '" + cn + "', "
402 + "methodName: '" + mn + "', "
403 + "request: " + caseNmbr
405 if (mi.args != null) {
406 w.write(", args: [");
408 for (String a : mi.args) {
417 if (mi.html != null) {
418 w.write(", html: '");
419 w.write(encodeJSON(mi.html));
426 this.brwsr = launchServerAndBrwsr(server, "/execute");
429 private static String encodeJSON(String in) {
430 StringBuilder sb = new StringBuilder();
431 for (int i = 0; i < in.length(); i++) {
432 char ch = in.charAt(i);
433 if (ch < 32 || ch == '\'' || ch == '"') {
435 String hs = "0000" + Integer.toHexString(ch);
436 hs = hs.substring(hs.length() - 4);
442 return sb.toString();
446 public void shutdown() throws IOException {
447 synchronized (this) {
448 if (flushing != null) {
449 flushing.interrupt();
455 int prev = methods.size();
457 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
460 } catch (InterruptedException ex) {
461 throw new IOException(ex);
463 if (prev == methods.size()) {
466 "Timeout and no test has been executed meanwhile (at {0}). Giving up.",
472 "Timeout, but tests got from {0} to {1}. Trying again.",
473 new Object[]{prev, methods.size()}
476 stopServerAndBrwsr(server, brwsr);
479 static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
485 if (ch == '$' && params.length > 0) {
486 int cnt = is.read() - '0';
487 if (baseURL != null && cnt == 'U' - '0') {
488 os.write(baseURL.getBytes("UTF-8"));
490 if (cnt >= 0 && cnt < params.length) {
491 os.write(params[cnt].getBytes("UTF-8"));
503 private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
505 URI uri = pageURL("http", server, page);
506 return showBrwsr(uri);
508 private static String toUTF8(String value) throws UnsupportedEncodingException {
509 byte[] arr = new byte[value.length()];
510 for (int i = 0; i < arr.length; i++) {
511 arr[i] = (byte)value.charAt(i);
513 return new String(arr, "UTF-8");
516 private static String decodeURL(String s) {
518 int pos = s.indexOf('%');
522 int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
523 s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
527 private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
531 Process process = (Process)brwsr[0];
534 InputStream stdout = process.getInputStream();
535 InputStream stderr = process.getErrorStream();
536 drain("StdOut", stdout);
537 drain("StdErr", stderr);
541 res = process.waitFor();
542 } catch (InterruptedException ex) {
543 throw new IOException(ex);
545 LOG.log(Level.INFO, "Exit code: {0}", res);
547 deleteTree((File)brwsr[1]);
550 private static void drain(String name, InputStream is) throws IOException {
551 int av = is.available();
553 StringBuilder sb = new StringBuilder();
554 sb.append("v== ").append(name).append(" ==v\n");
556 sb.append((char)is.read());
558 sb.append("\n^== ").append(name).append(" ==^");
559 LOG.log(Level.INFO, sb.toString());
563 private void deleteTree(File file) {
567 File[] arr = file.listFiles();
577 public HttpServer call() throws Exception {
582 public synchronized void flush() throws IOException {
583 flushing = Thread.currentThread();
584 while (flushing == Thread.currentThread()) {
587 } catch (InterruptedException ex) {
588 LOG.log(Level.FINE, null, ex);
594 public void close() throws IOException {
598 protected Object[] showBrwsr(URI uri) throws IOException {
599 LOG.log(Level.INFO, "Showing {0}", uri);
602 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
603 System.getProperty("java.vm.name"),
604 System.getProperty("java.vm.vendor"),
605 System.getProperty("java.vm.version"),
607 java.awt.Desktop.getDesktop().browse(uri);
608 LOG.log(Level.INFO, "Desktop.browse successfully finished");
610 } catch (UnsupportedOperationException ex) {
611 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
612 LOG.log(Level.FINE, null, ex);
613 } catch (IOException ex) {
614 LOG.log(Level.INFO, "Desktop.browse failed: {0}", ex.getMessage());
615 LOG.log(Level.FINE, null, ex);
619 String cmdName = cmd == null ? "xdg-open" : cmd;
621 cmdName, uri.toString()
623 LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
624 final Process process = Runtime.getRuntime().exec(cmdArr);
625 return new Object[] { process, null };
629 abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader, String url, boolean unitTestMode) throws IOException;
630 abstract String harnessResource();
631 Object compileJar(URL jar, URL precompiled) throws IOException {
634 String compileFromClassPath(URL f, Res loader) throws IOException {
638 private static URI pageURL(String protocol, HttpServer server, final String page) {
639 NetworkListener listener = server.getListeners().iterator().next();
640 int port = listener.getPort();
642 return new URI(protocol + "://localhost:" + port + page);
643 } catch (URISyntaxException ex) {
644 throw new IllegalStateException(ex);
649 private final Set<URL> ignore = new HashSet<URL>();
651 Object compileJar(URL jarURL) throws IOException {
652 List<String[]> libraries = new ArrayList<String[]>();
653 Map<String,Object[]> osgiJars = new HashMap<String, Object[]>();
654 for (ClassLoader loader : loaders) {
655 Enumeration<URL> en = loader.getResources("META-INF/MANIFEST.MF");
656 while (en.hasMoreElements()) {
657 URL e = en.nextElement();
658 Manifest mf = new Manifest(e.openStream());
659 for (Map.Entry<String, Attributes> entrySet : mf.getEntries().entrySet()) {
660 String key = entrySet.getKey();
661 Attributes attr = entrySet.getValue();
663 final String a = attr.getValue("Bck2BrwsrArtifactId");
664 final String g = attr.getValue("Bck2BrwsrGroupId");
665 final String v = attr.getValue("Bck2BrwsrVersion");
666 final String d = attr.getValue("Bck2BrwsrDebug");
667 final String n = attr.getValue("Bck2BrwsrName");
669 if (g != null && a != null && v != null && "true".equals(d)) {
670 libraries.add(new String[] {
675 final Attributes main = mf.getMainAttributes();
676 String symbol = main.getValue("Bundle-SymbolicName");
678 if (symbol == null) {
679 symbol = main.getValue("OpenIDE-Module-Name");
680 version = main.getValue("OpenIDE-Module-SpecificationVersion");
682 version = main.getValue("Bundle-Version");
684 if (symbol != null) {
685 osgiJars.put(symbol, new Object[] { e, version });
689 URL precompiled = null;
690 for (ClassLoader loader : loaders) {
691 for (String[] lib : libraries) {
692 final String res = "META-INF/maven/" + lib[1] + "/" + lib[0] + "/pom.properties";
693 URL props = loader.getResource(res);
695 URLConnection c = props.openConnection();
696 Properties load = new Properties();
697 final InputStream is = c.getInputStream();
700 if (lib[2].equals(load.getProperty("version"))) {
701 if (c instanceof JarURLConnection) {
702 final URL definedInURL = ((JarURLConnection)c).getJarFileURL();
703 if (definedInURL.equals(jarURL)) {
704 precompiled = loader.getResource(lib[3]);
711 if (precompiled == null) {
712 for (ClassLoader loader : loaders) {
713 for (String[] lib : libraries) {
714 Object[] urlVersion = osgiJars.get(lib[4]);
715 String expectVersion = lib[2];
716 if (expectVersion.endsWith("-SNAPSHOT")) {
717 expectVersion = expectVersion.substring(0, expectVersion.length() - 9);
719 if (urlVersion != null && urlVersion[1].toString().startsWith(expectVersion)) {
720 precompiled = loader.getResource(lib[3]);
725 Object ret = BaseHTTPLauncher.this.compileJar(jarURL, precompiled);
729 String compileFromClassPath(URL f) throws IOException {
730 return BaseHTTPLauncher.this.compileFromClassPath(f, this);
732 public URL get(String resource, int skip) throws IOException {
733 if (!resource.endsWith(".class")) {
734 return getResource(resource, skip);
737 for (ClassLoader l : loaders) {
738 Enumeration<URL> en = l.getResources(resource);
739 while (en.hasMoreElements()) {
740 u = en.nextElement();
741 if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
747 if (u.toExternalForm().contains("rt.jar")) {
748 LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
753 throw new IOException("Can't find " + resource);
755 private URL getResource(String resource, int skip) throws IOException {
756 for (ClassLoader l : loaders) {
757 Enumeration<URL> en = l.getResources(resource);
758 while (en.hasMoreElements()) {
759 final URL now = en.nextElement();
760 if (now.toExternalForm().contains("sisu-inject-bean")) {
761 // certainly we don't want this resource, as that
762 // module is not compiled with target 1.6, currently
765 if (now.getProtocol().equals("jar")) {
766 JarURLConnection juc = (JarURLConnection) now.openConnection();
767 if (now.getFile().endsWith(".class") && ignore.contains(juc.getJarFileURL())) {
776 throw new IOException("Not found (anymore of) " + resource);
780 private static class Page extends HttpHandler {
781 final String resource;
782 private final String[] args;
783 private final Res res;
785 public Page(Res res, String resource, String... args) {
787 this.resource = resource;
788 this.args = args.length == 0 ? new String[] { "$0" } : args;
792 public void service(Request request, Response response) throws Exception {
793 String r = computePage(request);
794 if (r.startsWith("/")) {
797 String[] replace = {};
798 if (r.endsWith(".html")) {
799 response.setContentType("text/html");
800 LOG.info("Content type text/html");
803 if (r.endsWith(".xhtml")) {
804 response.setContentType("application/xhtml+xml");
805 LOG.info("Content type application/xhtml+xml");
808 OutputStream os = response.getOutputStream();
810 InputStream is = res.get(r, 0).openStream();
811 copyStream(is, os, request.getRequestURL().toString(), replace);
812 } catch (IOException ex) {
813 response.setDetailMessage(ex.getLocalizedMessage());
815 response.setStatus(404);
819 protected String computePage(Request request) {
822 r = request.getHttpHandlerPath();
828 private static class SubTree extends Page {
830 public SubTree(Res res, String resource, String... args) {
831 super(res, resource, args);
835 protected String computePage(Request request) {
836 return resource + request.getHttpHandlerPath();
842 private class VMAndPages extends StaticHttpHandler {
843 private final boolean unitTestMode;
844 private String vmResource;
846 public VMAndPages(boolean unitTestMode) {
847 super((String[]) null);
848 this.unitTestMode = unitTestMode;
852 public void service(Request request, Response response) throws Exception {
853 if ("true".equals(request.getParameter("exit"))) {
854 LOG.info("Exit request received. Shutting down!");
857 if (request.getRequestURI().equals(vmResource)) {
858 response.setCharacterEncoding("UTF-8");
859 response.setContentType("text/javascript");
860 StringBuilder sb = new StringBuilder();
861 generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources, request.getRequestURL().toString(), unitTestMode);
862 response.getWriter().write(sb.toString());
864 super.service(request, response);
868 private void registerVM(String vmResource) {
869 this.vmResource = vmResource;
873 private static class Classes extends HttpHandler {
874 private final Res loader;
876 public Classes(Res loader) {
877 this.loader = loader;
881 public void service(Request request, Response response) throws Exception {
882 String res = request.getHttpHandlerPath();
883 if (res.startsWith("/")) {
884 res = res.substring(1);
886 String skip = request.getParameter("skip");
887 int skipCnt = skip == null ? 0 : Integer.parseInt(skip);
888 URL url = loader.get(res, skipCnt);
889 if (url != null && !res.equals("META-INF/MANIFEST.MF")) try {
890 response.setCharacterEncoding("UTF-8");
891 if (url.getProtocol().equals("jar")) {
892 JarURLConnection juc = (JarURLConnection) url.openConnection();
895 s = loader.compileJar(juc.getJarFileURL());
896 } catch (IOException iOException) {
897 throw new IOException("Can't compile " + url.toExternalForm(), iOException);
899 if (s instanceof String) {
900 Writer w = response.getWriter();
905 if (s instanceof InputStream) {
906 copyStream((InputStream) s, response.getOutputStream(), null);
910 if (url.getProtocol().equals("file")) {
911 final String filePart = url.getFile();
912 if (filePart.endsWith(res)) {
917 filePart.substring(0, filePart.length() - res.length())
920 String s = loader.compileFromClassPath(url);
922 Writer w = response.getWriter();
928 } catch (IOException ex) {
929 LOG.log(Level.SEVERE, "Cannot handle " + res, ex);
931 InputStream is = null;
934 throw new IOException("Resource not found");
936 is = url.openStream();
937 response.setContentType("text/javascript");
938 Writer w = response.getWriter();
940 for (int i = 0;; i++) {
954 w.append(Integer.toString(b));
957 } catch (IOException ex) {
958 response.setStatus(HttpStatus.NOT_FOUND_404);
960 response.setDetailMessage(ex.getMessage());
969 private static class WS extends WebSocketApplication {
971 private final Resource r;
973 private WS(Resource r) {
978 public void onMessage(WebSocket socket, String text) {
980 r.httpContent.reset();
981 ByteArrayOutputStream out = new ByteArrayOutputStream();
982 copyStream(r.httpContent, out, null, text);
983 String s = new String(out.toByteArray(), "UTF-8");
985 } catch (IOException ex) {
986 LOG.log(Level.WARNING, null, ex);