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