dew/src/main/java/org/apidesign/bck2brwsr/dew/DewLauncher.java
author Lubomir Nerad <lubomir.nerad@oracle.com>
Thu, 25 Apr 2013 16:17:48 +0200
branchclosure
changeset 1020 a6bacea2518f
parent 580 2f42cd9b5531
child 1029 b1fe994d4267
permissions -rw-r--r--
Initial structure for extension modules
     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         @Override
   127         public String getModule(String resource) throws IOException {
   128             return null;
   129         }
   130     }
   131 
   132     private static class VM extends HttpHandler {
   133         private final String bck2brwsr;
   134 
   135         public VM(Res loader) throws IOException {
   136             StringBuilder sb = new StringBuilder();
   137             Bck2Brwsr.generate(sb, loader);
   138             this.bck2brwsr = sb.toString();
   139         }
   140 
   141         @Override
   142         public void service(Request request, Response response) throws Exception {
   143             response.setCharacterEncoding("UTF-8");
   144             response.setContentType("text/javascript");
   145             response.getWriter().write(bck2brwsr);
   146         }
   147     }
   148     private static class VMInit extends HttpHandler {
   149         public VMInit() {
   150         }
   151 
   152         @Override
   153         public void service(Request request, Response response) throws Exception {
   154             response.setCharacterEncoding("UTF-8");
   155             response.setContentType("text/javascript");
   156             response.getWriter().append(
   157                 "function ldCls(res) {\n"
   158                 + "  var request = new XMLHttpRequest();\n"
   159                 + "  request.open('GET', '/classes/' + res, false);\n"
   160                 + "  request.send();\n"
   161                 + "  var arr = eval('(' + request.responseText + ')');\n"
   162                 + "  return arr;\n"
   163                 + "}\n"
   164                 + "var vm = new bck2brwsr(ldCls);\n");
   165         }
   166     }
   167 
   168     private static class Classes extends HttpHandler {
   169         private final Res loader;
   170 
   171         public Classes(Res loader) {
   172             this.loader = loader;
   173         }
   174 
   175         @Override
   176         public void service(Request request, Response response) throws Exception {
   177             String res = request.getHttpHandlerPath();
   178             if (res.startsWith("/")) {
   179                 res = res.substring(1);
   180             }
   181             try (InputStream is = loader.get(res)) {
   182                 response.setContentType("text/javascript");
   183                 Writer w = response.getWriter();
   184                 w.append("[");
   185                 for (int i = 0;; i++) {
   186                     int b = is.read();
   187                     if (b == -1) {
   188                         break;
   189                     }
   190                     if (i > 0) {
   191                         w.append(", ");
   192                     }
   193                     if (i % 20 == 0) {
   194                         w.write("\n");
   195                     }
   196                     if (b > 127) {
   197                         b = b - 256;
   198                     }
   199                     w.append(Integer.toString(b));
   200                 }
   201                 w.append("\n]");
   202             } catch (IOException ex) {
   203                 response.setError();
   204                 response.setDetailMessage(ex.getMessage());
   205             }
   206         }
   207     }
   208 }