dew/src/main/java/org/apidesign/bck2brwsr/dew/DewLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 23 Jan 2013 14:10:15 +0100
branchdew
changeset 546 79e5a4aae48d
parent 544 dew/src/main/java/org/apidesign/bck2brwsr/launcher/Bck2BrwsrLauncher.java@08ffdc3938e7
child 580 2f42cd9b5531
permissions -rw-r--r--
Keeping just the part of the server that is needed for the dew system
     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) {
    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 Res loader;
   129 
   130         public VM(Res loader) {
   131             this.loader = loader;
   132         }
   133 
   134         @Override
   135         public void service(Request request, Response response) throws Exception {
   136             response.setCharacterEncoding("UTF-8");
   137             response.setContentType("text/javascript");
   138             Bck2Brwsr.generate(response.getWriter(), loader);
   139         }
   140     }
   141     private static class VMInit extends HttpHandler {
   142         public VMInit() {
   143         }
   144 
   145         @Override
   146         public void service(Request request, Response response) throws Exception {
   147             response.setCharacterEncoding("UTF-8");
   148             response.setContentType("text/javascript");
   149             response.getWriter().append(
   150                 "function ldCls(res) {\n"
   151                 + "  var request = new XMLHttpRequest();\n"
   152                 + "  request.open('GET', '/classes/' + res, false);\n"
   153                 + "  request.send();\n"
   154                 + "  var arr = eval('(' + request.responseText + ')');\n"
   155                 + "  return arr;\n"
   156                 + "}\n"
   157                 + "var vm = new bck2brwsr(ldCls);\n");
   158         }
   159     }
   160 
   161     private static class Classes extends HttpHandler {
   162         private final Res loader;
   163 
   164         public Classes(Res loader) {
   165             this.loader = loader;
   166         }
   167 
   168         @Override
   169         public void service(Request request, Response response) throws Exception {
   170             String res = request.getHttpHandlerPath();
   171             if (res.startsWith("/")) {
   172                 res = res.substring(1);
   173             }
   174             try (InputStream is = loader.get(res)) {
   175                 response.setContentType("text/javascript");
   176                 Writer w = response.getWriter();
   177                 w.append("[");
   178                 for (int i = 0;; i++) {
   179                     int b = is.read();
   180                     if (b == -1) {
   181                         break;
   182                     }
   183                     if (i > 0) {
   184                         w.append(", ");
   185                     }
   186                     if (i % 20 == 0) {
   187                         w.write("\n");
   188                     }
   189                     if (b > 127) {
   190                         b = b - 256;
   191                     }
   192                     w.append(Integer.toString(b));
   193                 }
   194                 w.append("\n]");
   195             } catch (IOException ex) {
   196                 response.setError();
   197                 response.setDetailMessage(ex.getMessage());
   198             }
   199         }
   200     }
   201 }