dew/src/main/java/org/apidesign/bck2brwsr/dew/DewLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 25 Jan 2013 10:51:20 +0100
changeset 580 2f42cd9b5531
parent 546 79e5a4aae48d
child 1020 a6bacea2518f
permissions -rw-r--r--
Keep the VM code, don't regenerate it every time
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     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.
     8  *
     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.
    13  *
    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.
    17  */
    18 package org.apidesign.bck2brwsr.dew;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import java.io.Writer;
    23 import java.net.URI;
    24 import java.net.URISyntaxException;
    25 import java.net.URL;
    26 import java.util.Arrays;
    27 import java.util.Enumeration;
    28 import java.util.LinkedHashSet;
    29 import java.util.Set;
    30 import java.util.logging.Level;
    31 import java.util.logging.Logger;
    32 import org.apidesign.vm4brwsr.Bck2Brwsr;
    33 import org.glassfish.grizzly.PortRange;
    34 import org.glassfish.grizzly.http.server.HttpHandler;
    35 import org.glassfish.grizzly.http.server.HttpServer;
    36 import org.glassfish.grizzly.http.server.NetworkListener;
    37 import org.glassfish.grizzly.http.server.Request;
    38 import org.glassfish.grizzly.http.server.Response;
    39 import org.glassfish.grizzly.http.server.ServerConfiguration;
    40 
    41 /**
    42  * Lightweight server to launch dew - the Development Environment for Web.
    43  */
    44 final class DewLauncher {
    45     private static final Logger LOG = Logger.getLogger(DewLauncher.class.getName());
    46     private Set<ClassLoader> loaders = new LinkedHashSet<>();
    47     private Set<Bck2Brwsr.Resources> xRes = new LinkedHashSet<>();
    48     private final Res resources = new Res();
    49     private final String cmd;
    50 
    51     public DewLauncher(String cmd) {
    52         this.cmd = cmd;
    53     }
    54     
    55     public void addClassLoader(ClassLoader url) {
    56         this.loaders.add(url);
    57     }
    58 
    59     final HttpServer initServer(Bck2Brwsr.Resources... extraResources) throws IOException {
    60         xRes.addAll(Arrays.asList(extraResources));
    61         
    62         HttpServer s = HttpServer.createSimpleServer(".", new PortRange(8080, 65535));
    63 
    64         final ServerConfiguration conf = s.getServerConfiguration();
    65         conf.addHttpHandler(new VM(resources), "/bck2brwsr.js");
    66         conf.addHttpHandler(new VMInit(), "/vm.js");
    67         conf.addHttpHandler(new Classes(resources), "/classes/");
    68         return s;
    69     }
    70     
    71     final Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
    72         server.start();
    73         NetworkListener listener = server.getListeners().iterator().next();
    74         int port = listener.getPort();
    75         
    76         URI uri = new URI("http://localhost:" + port + page);
    77         LOG.log(Level.INFO, "Showing {0}", uri);
    78         if (cmd == null) {
    79             try {
    80                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
    81                     System.getProperty("java.vm.name"),
    82                     System.getProperty("java.vm.vendor"),
    83                     System.getProperty("java.vm.version"),
    84                 });
    85                 java.awt.Desktop.getDesktop().browse(uri);
    86                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
    87                 return null;
    88             } catch (UnsupportedOperationException ex) {
    89                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
    90                 LOG.log(Level.FINE, null, ex);
    91             }
    92         }
    93         {
    94             String cmdName = cmd == null ? "xdg-open" : cmd;
    95             String[] cmdArr = { 
    96                 cmdName, uri.toString()
    97             };
    98             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
    99             final Process process = Runtime.getRuntime().exec(cmdArr);
   100             return new Object[] { process, null };
   101         }
   102     }
   103 
   104     private class Res implements Bck2Brwsr.Resources {
   105         @Override
   106         public InputStream get(String resource) throws IOException {
   107             for (ClassLoader l : loaders) {
   108                 URL u = null;
   109                 Enumeration<URL> en = l.getResources(resource);
   110                 while (en.hasMoreElements()) {
   111                     u = en.nextElement();
   112                 }
   113                 if (u != null) {
   114                     return u.openStream();
   115                 }
   116             }
   117             for (Bck2Brwsr.Resources r : xRes) {
   118                 InputStream is = r.get(resource);
   119                 if (is != null) {
   120                     return is;
   121                 }
   122             }
   123             throw new IOException("Can't find " + resource);
   124         }
   125     }
   126 
   127     private static class VM extends HttpHandler {
   128         private final String bck2brwsr;
   129 
   130         public VM(Res loader) throws IOException {
   131             StringBuilder sb = new StringBuilder();
   132             Bck2Brwsr.generate(sb, loader);
   133             this.bck2brwsr = sb.toString();
   134         }
   135 
   136         @Override
   137         public void service(Request request, Response response) throws Exception {
   138             response.setCharacterEncoding("UTF-8");
   139             response.setContentType("text/javascript");
   140             response.getWriter().write(bck2brwsr);
   141         }
   142     }
   143     private static class VMInit extends HttpHandler {
   144         public VMInit() {
   145         }
   146 
   147         @Override
   148         public void service(Request request, Response response) throws Exception {
   149             response.setCharacterEncoding("UTF-8");
   150             response.setContentType("text/javascript");
   151             response.getWriter().append(
   152                 "function ldCls(res) {\n"
   153                 + "  var request = new XMLHttpRequest();\n"
   154                 + "  request.open('GET', '/classes/' + res, false);\n"
   155                 + "  request.send();\n"
   156                 + "  var arr = eval('(' + request.responseText + ')');\n"
   157                 + "  return arr;\n"
   158                 + "}\n"
   159                 + "var vm = new bck2brwsr(ldCls);\n");
   160         }
   161     }
   162 
   163     private static class Classes extends HttpHandler {
   164         private final Res loader;
   165 
   166         public Classes(Res loader) {
   167             this.loader = loader;
   168         }
   169 
   170         @Override
   171         public void service(Request request, Response response) throws Exception {
   172             String res = request.getHttpHandlerPath();
   173             if (res.startsWith("/")) {
   174                 res = res.substring(1);
   175             }
   176             try (InputStream is = loader.get(res)) {
   177                 response.setContentType("text/javascript");
   178                 Writer w = response.getWriter();
   179                 w.append("[");
   180                 for (int i = 0;; i++) {
   181                     int b = is.read();
   182                     if (b == -1) {
   183                         break;
   184                     }
   185                     if (i > 0) {
   186                         w.append(", ");
   187                     }
   188                     if (i % 20 == 0) {
   189                         w.write("\n");
   190                     }
   191                     if (b > 127) {
   192                         b = b - 256;
   193                     }
   194                     w.append(Integer.toString(b));
   195                 }
   196                 w.append("\n]");
   197             } catch (IOException ex) {
   198                 response.setError();
   199                 response.setDetailMessage(ex.getMessage());
   200             }
   201         }
   202     }
   203 }