launcher/http/src/main/java/org/apidesign/bck2brwsr/launcher/JSLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 17 Jan 2017 07:04:06 +0100
changeset 1985 cd1cc103a03c
parent 1860 4ce38f21f4cd
permissions -rw-r--r--
Implementation of ClassValue for bck2brwsr
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012-2015 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.launcher;
    19 
    20 import org.apidesign.bck2brwsr.launcher.impl.Console;
    21 import java.io.IOException;
    22 import java.io.InputStream;
    23 import java.net.URL;
    24 import java.util.Enumeration;
    25 import java.util.LinkedHashSet;
    26 import java.util.Set;
    27 import java.util.logging.Level;
    28 import java.util.logging.Logger;
    29 import javax.script.Invocable;
    30 import javax.script.ScriptEngine;
    31 import javax.script.ScriptEngineManager;
    32 import javax.script.ScriptException;
    33 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
    34 import org.apidesign.vm4brwsr.Bck2Brwsr;
    35 
    36 /**
    37  * Tests execution in Java's internal scripting engine.
    38  */
    39 @ExtraJavaScript(processByteCode = false, resource="")
    40 final class JSLauncher extends Launcher {
    41     private static final Logger LOG = Logger.getLogger(JSLauncher.class.getName());
    42     private Set<ClassLoader> loaders = new LinkedHashSet<>();
    43     private final Res resources = new Res();
    44     private Invocable code;
    45     private StringBuilder codeSeq;
    46     private Object console;
    47 
    48     JSLauncher() {
    49         addClassLoader(Bck2Brwsr.class.getClassLoader());
    50     }
    51     
    52     @Override InvocationContext runMethod(InvocationContext mi) {
    53         loaders.add(mi.clazz.getClassLoader());
    54         try {
    55             long time = System.currentTimeMillis();
    56             LOG.log(Level.FINE, "Invoking {0}.{1}", new Object[]{mi.clazz.getName(), mi.methodName});
    57             String res = code.invokeMethod(
    58                 console,
    59                 "invoke__Ljava_lang_String_2Ljava_lang_String_2Ljava_lang_String_2",
    60                 mi.clazz.getName(), mi.methodName).toString();
    61             time = System.currentTimeMillis() - time;
    62             LOG.log(Level.FINE, "Resut of {0}.{1} = {2} in {3} ms", new Object[]{mi.clazz.getName(), mi.methodName, res, time});
    63             mi.result(res, (int)time, null);
    64         } catch (ScriptException | NoSuchMethodException ex) {
    65             mi.result(null, -1, ex);
    66         }
    67         return mi;
    68     }
    69     
    70     public void addClassLoader(ClassLoader url) {
    71         this.loaders.add(url);
    72     }
    73 
    74     @Override
    75     public void initialize() throws IOException {
    76         try {
    77             initRhino();
    78         } catch (Exception ex) {
    79             if (ex instanceof IOException) {
    80                 throw (IOException)ex;
    81             }
    82             if (ex instanceof RuntimeException) {
    83                 throw (RuntimeException)ex;
    84             }
    85             throw new IOException(ex);
    86         }
    87     }
    88     
    89     private void initRhino() throws IOException, ScriptException, NoSuchMethodException {
    90         StringBuilder sb = new StringBuilder();
    91         Bck2Brwsr.generate(sb, new Res());
    92 
    93         ScriptEngineManager sem = new ScriptEngineManager();
    94         ScriptEngine mach = sem.getEngineByExtension("js");
    95 
    96         sb.append(
    97               "\nvar vm = new bck2brwsr(org.apidesign.bck2brwsr.launcher.impl.Console.read);"
    98             + "\nfunction initVM() { return vm; };"
    99             + "\n");
   100 
   101         Object res = mach.eval(sb.toString());
   102         if (!(mach instanceof Invocable)) {
   103             throw new IOException("It is invocable object: " + res);
   104         }
   105         code = (Invocable) mach;
   106         codeSeq = sb;
   107         
   108         Object vm = code.invokeFunction("initVM");
   109         console = code.invokeMethod(vm, "loadClass", Console.class.getName());
   110     }
   111 
   112     @Override
   113     public void shutdown() throws IOException {
   114     }
   115 
   116     @Override
   117     public String toString() {
   118         return codeSeq.toString();
   119     }
   120     
   121     private class Res implements Bck2Brwsr.Resources {
   122         @Override
   123         public InputStream get(String resource) throws IOException {
   124             for (ClassLoader l : loaders) {
   125                 URL u = null;
   126                 Enumeration<URL> en = l.getResources(resource);
   127                 while (en.hasMoreElements()) {
   128                     u = en.nextElement();
   129                 }
   130                 if (u != null) {
   131                     if (u.toExternalForm().contains("/rt.jar")) {
   132                         LOG.log(Level.WARNING, "No fallback to bootclasspath for {0}", u);
   133                         return null;
   134                     }
   135                     return u.openStream();
   136                 }
   137             }
   138             throw new IOException("Can't find " + resource);
   139         }
   140     }
   141 }