rt/vm/src/main/java/org/apidesign/vm4brwsr/Bck2Brwsr.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 22 Nov 2013 11:15:04 +0100
changeset 1413 b597de629d33
parent 1365 4393b7db103b
child 1513 ba912ef24b27
permissions -rw-r--r--
Removing unused import
     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.vm4brwsr;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 
    23 /** Build your own virtual machine! Use methods in this class to generate
    24  * a skeleton JVM in JavaScript that contains pre-compiled classes of your
    25  * choice. The generated script defines one JavaScript method that can
    26  * be used to bootstrap and load the virtual machine: <pre>
    27  * var vm = bck2brwsr();
    28  * var main = vm.loadClass('org.your.pkg.Main');
    29  * main.main__V_3Ljava_lang_String_2(null);
    30  * </pre>
    31  * In case one wants to initialize the virtual machine with ability to
    32  * load classes lazily when needed, one can provide a loader function to
    33  * when creating the virtual machine: <pre>
    34  * var vm = bck2brwsr(function(resource) { 
    35  *   return null; // byte[] for the resource
    36  * });
    37  * </pre>
    38  * In this scenario, when a request for an unknown class is made, the loader
    39  * function is asked for its byte code and the system dynamically transforms
    40  * it to JavaScript.
    41  * <p>
    42  * Instead of a loader function, one can also provide a URL to a JAR file.
    43  * The <code>bck2brwsr</code> system will do its best to download the file
    44  * and provide loader function for it automatically.
    45  * <p>
    46  * One can provide as many loader functions and JAR URL references as necessary.
    47  * Then the initialization code would look like:<pre>
    48  * var vm = bck2brwsr(url1, url2, fnctn1, url3, functn2);
    49  * </pre>
    50  * The provided URLs and loader functions will be consulted one by one.
    51  *
    52  * @author Jaroslav Tulach <jtulach@netbeans.org>
    53  */
    54 public final class Bck2Brwsr {
    55     private final ObfuscationLevel level;
    56     private final StringArray classes;
    57     private final Resources res;
    58 
    59     private Bck2Brwsr(ObfuscationLevel level, StringArray classes, Resources resources) {
    60         this.level = level;
    61         this.classes = classes;
    62         this.res = resources;
    63     }
    64     
    65     /** Helper method to generate virtual machine from bytes served by a <code>resources</code>
    66      * provider.
    67      *
    68      * @param out the output to write the generated JavaScript to
    69      * @param resources provider of class files to use
    70      * @param classes additional classes to include in the generated script
    71      * @throws IOException I/O exception can be thrown when something goes wrong
    72      */
    73     public static void generate(Appendable out, Resources resources, String... classes) throws IOException {
    74         newCompiler().resources(resources).addRootClasses(classes).generate(out);
    75     }
    76 
    77     /** Helper method to generate virtual machine from bytes served by a class loader.
    78      *
    79      * @param out the output to write the generated JavaScript to
    80      * @param loader class loader to load needed classes from
    81      * @param classes additional classes to include in the generated script
    82      * @throws IOException I/O exception can be thrown when something goes wrong
    83      */
    84     public static void generate(Appendable out, ClassLoader loader, String... classes) throws IOException {
    85         newCompiler().resources(loader).addRootClasses(classes).generate(out);
    86     }
    87     
    88     /** Creates new instance of Bck2Brwsr compiler which is ready to generate
    89      * empty Bck2Brwsr virtual machine. The instance can be further
    90      * configured by calling chain of methods. For example: 
    91      * <pre>
    92      * {@link #createCompiler()}.{@link #resources(org.apidesign.vm4brwsr.Bck2Brwsr.Resources) resources(loader)}.{@link #addRootClasses(java.lang.String[]) addRootClasses("your/Clazz")}.{@link #generate(java.lang.Appendable) generate(out)};
    93      * </pre>
    94      * 
    95      * @return new instance of the Bck2Brwsr compiler
    96      * @since 0.5
    97      */
    98     public static Bck2Brwsr newCompiler() {
    99         StringArray arr = StringArray.asList(VM.class.getName().replace('.', '/'));
   100         return new Bck2Brwsr(ObfuscationLevel.NONE, arr, null);
   101     }
   102 
   103     /** Creates new instance of the Bck2Brwsr compiler which inherits
   104      * all values from <code>this</code> instance and adds additional classes 
   105      * to the list of those that should be compiled by the {@link #generate(java.lang.Appendable)} 
   106      * method.
   107      * 
   108      * @param classes the classes to add to the compilation
   109      * @return new instance of the compiler
   110      */
   111     public Bck2Brwsr addRootClasses(String... classes) {
   112         if (classes.length == 0) {
   113             return this;
   114         } else {
   115             return new Bck2Brwsr(level, this.classes.addAndNew(classes), res);
   116         }
   117     }
   118     
   119     /** Changes the obfuscation level for the compiler by creating new instance
   120      * which inherits all values from <code>this</code> and adjust the level
   121      * of obfuscation.
   122      * 
   123      * @param level the new level of obfuscation
   124      * @return new instance of the compiler with changed level of obfuscation
   125      * @since 0.5
   126      */
   127     public Bck2Brwsr obfuscation(ObfuscationLevel level) {
   128         return new Bck2Brwsr(level, classes, res);
   129     }
   130     
   131     /** A way to change the provider of additional resources (classes) for the 
   132      * compiler. 
   133      * 
   134      * @param res the implementation of resources provider
   135      * @return new instance of the compiler with all values remaining the same, just 
   136      *   with different resources provider
   137      * @since 0.5
   138      */
   139     public Bck2Brwsr resources(Resources res) {
   140         return new Bck2Brwsr(level, classes, res);
   141     }
   142 
   143     /** A way to change the provider of additional resources (classes) for the 
   144      * compiler by specifying classloader to use for loading them.
   145      * 
   146      * @param loader class loader to load the resources from
   147      * @return new instance of the compiler with all values being the same, just 
   148      *   different resources provider
   149      * @since 0.5
   150      */
   151     public Bck2Brwsr resources(final ClassLoader loader) {
   152         return resources(loader, false);
   153     }
   154 
   155     /** A way to change the provider of additional resources (classes) for the 
   156      * compiler by specifying classloader to use for loading them.
   157      * 
   158      * @param loader class loader to load the resources from
   159      * @param ignoreBootClassPath <code>true</code> if classes loaded
   160      *    from <code>rt.jar</code> 
   161      * @return new instance of the compiler with all values being the same, just 
   162      *   different resources provider
   163      * @since 0.9
   164      */
   165     public Bck2Brwsr resources(final ClassLoader loader, boolean ignoreBootClassPath) {
   166         return resources(new LdrRsrcs(loader, ignoreBootClassPath));
   167     }
   168     
   169     /** Generates virtual machine based on previous configuration of the 
   170      * compiler.
   171      * 
   172      * @param out the output to write the generated JavaScript to
   173      * @since 0.5
   174      */
   175     public void generate(Appendable out) throws IOException {
   176         Resources r = res != null ? res : new LdrRsrcs(Bck2Brwsr.class.getClassLoader(), false);
   177         if (level != ObfuscationLevel.NONE) {
   178             try {
   179                 ClosureWrapper.produceTo(out, level, r, classes);
   180                 return;
   181             } catch (IOException ex) {
   182                 throw ex;
   183             } catch (Throwable ex) {
   184                 out.append("/* Failed to obfuscate: " + ex.getMessage()
   185                                + " */\n");
   186             }
   187         }
   188 
   189         VM.compile(r, out, classes);
   190     }
   191     
   192     /** Provider of resources (classes and other files). The 
   193      * {@link #generate(java.lang.Appendable, org.apidesign.vm4brwsr.Bck2Brwsr.Resources, java.lang.String[]) 
   194      * generator method} will call back here for all classes needed during
   195      * translation to JavaScript.
   196      */
   197     public interface Resources {
   198         /** Loads given resource (class or other file like image). The 
   199          * resource name to load bytes for the {@link String} class
   200          * would be <code>"java/lang/String.class"</code>.
   201          * 
   202          * @param resource path to resource to load
   203          * @return the input stream for the resource 
   204          * @throws IOException can be thrown if the loading fails on some error
   205          *   or the file cannot be found
   206          */
   207         public InputStream get(String resource) throws IOException;
   208     }
   209 }