rt/vm/src/main/java/org/apidesign/vm4brwsr/Zips.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 09 Oct 2013 17:28:39 +0200
changeset 1357 f5c3f68c0664
parent 772 d382dacfd73f
child 1358 65dd5a650eab
permissions -rw-r--r--
Conditional logging to run in a worker thread
     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.ByteArrayInputStream;
    21 import java.io.IOException;
    22 import java.io.InputStream;
    23 import java.net.URL;
    24 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    25 import org.apidesign.bck2brwsr.emul.zip.FastJar;
    26 
    27 /** Conversion from classpath to load function.
    28  *
    29  * @author Jaroslav Tulach <jtulach@netbeans.org>
    30  */
    31 final class Zips {
    32     private final FastJar fj;
    33 
    34     private Zips(String path, byte[] zipData) throws IOException {
    35         long bef = timeNow();
    36         fj = new FastJar(zipData);
    37         for (FastJar.Entry e : fj.list()) {
    38             putRes(e.name, e);
    39         }
    40         log("Iterating thru " + path + " took " + (timeNow() - bef) + "ms");
    41     }
    42     
    43     public static void init() {
    44     }
    45     @JavaScriptBody(args = { "arr" }, body = "return arr.length;")
    46     private static native int length(Object arr);
    47     @JavaScriptBody(args = { "arr", "index" }, body = "return arr[index];")
    48     private static native Object at(Object arr, int index);
    49     @JavaScriptBody(args = { "arr", "index", "value" }, body = "arr[index] = value; return value;")
    50     private static native Object set(Object arr, int index, Object value);
    51     
    52     public static byte[] loadFromCp(Object classpath, String res) 
    53     throws IOException, ClassNotFoundException {
    54         for (int i = 0; i < length(classpath); i++) {
    55             Object c = at(classpath, i);
    56             if (c instanceof String) {
    57                 try {
    58                     String url = (String)c;
    59                     final Zips z = toZip(url);
    60                     c = set(classpath, i, z);
    61                     final byte[] man = z.findRes("META-INF/MANIFEST.MF");
    62                     if (man != null) {
    63                         String mainClass = processClassPathAttr(man, url, classpath);
    64 //                        if (mainClass != null) {
    65 //                            Class.forName(mainClass);
    66 //                        }
    67                     }
    68                 } catch (IOException ex) {
    69                     set(classpath, i, ex);
    70                     log("Cannot load " + c + " - " + ex.getClass().getName() + ":" + ex.getMessage());
    71                 }
    72             }
    73             if (res != null) {
    74                 byte[] checkRes;
    75                 if (c instanceof Zips) {
    76                     checkRes = ((Zips)c).findRes(res);
    77                 } else {
    78                     checkRes = callFunction(c, res);
    79                 }
    80                 if (checkRes != null) {
    81                     return checkRes;
    82                 }
    83             }
    84         }
    85         return null;
    86     }
    87     
    88     @JavaScriptBody(args = { "fn", "res" }, body = 
    89         "if (typeof fn === 'function') return fn(res);\n"
    90       + "return null;"
    91     )
    92     private static native byte[] callFunction(Object fn, String res);
    93     
    94     @JavaScriptBody(args = { "msg" }, body = "if (console) console.log(msg.toString());")
    95     private static native void log(String msg);
    96 
    97     private byte[] findRes(String res) throws IOException {
    98         Object arr = findResImpl(res);
    99         if (arr instanceof FastJar.Entry) {
   100             long bef = timeNow();
   101             InputStream zip = fj.getInputStream((FastJar.Entry)arr);
   102             arr = readFully(new byte[512], zip);
   103             putRes(res, arr);
   104             log("Reading " + res + " took " + (timeNow() - bef) + "ms");
   105         }
   106         return (byte[]) arr;
   107     }
   108 
   109     @JavaScriptBody(args = { "res" }, body = "var r = this[res]; return r ? r : null;")
   110     private native Object findResImpl(String res);
   111 
   112     @JavaScriptBody(args = { "res", "arr" }, body = "this[res] = arr;")
   113     private native void putRes(String res, Object arr);
   114     
   115     private static Zips toZip(String path) throws IOException {
   116         URL u = new URL(path);
   117         byte[] zipData = (byte[]) u.getContent(new Class[] { byte[].class });
   118         return new Zips(path, zipData);
   119     }
   120 
   121     private static String processClassPathAttr(final byte[] man, String url, Object classpath) throws IOException {
   122         try (ParseMan is = new ParseMan(new ByteArrayInputStream(man))) {
   123             String cp = is.toString();
   124             if (cp != null) {
   125                 cp = cp.trim();
   126                 for (int p = 0; p < cp.length();) {
   127                     int n = cp.indexOf(' ', p);
   128                     if (n == -1) {
   129                         n = cp.length();
   130                     }
   131                     String el = cp.substring(p, n);
   132                     URL u = new URL(new URL(url), el);
   133                     classpath = addToArray(classpath, u.toString());
   134                     p = n + 1;
   135                 }
   136             }
   137             return is.getMainClass();
   138         }
   139     }
   140 
   141     private static Object addToArray(Object arr, String value) {
   142         final int last = length(arr);
   143         Object ret = enlargeArray(arr, last + 1);
   144         set(ret, last, value);
   145         return ret;
   146     }
   147 
   148     @JavaScriptBody(args = { "arr", "len" }, body = "while (arr.length < len) arr.push(null); return arr;")
   149     private static native Object enlargeArray(Object arr, int len);
   150     @JavaScriptBody(args = { "arr", "len" }, body = "while (arr.length < len) arr.push(0);")
   151     private static native void enlargeBytes(byte[] arr, int len);
   152 
   153     @JavaScriptBody(args = { "arr", "len" }, body = "arr.splice(len, arr.length - len);")
   154     private static native void sliceArray(byte[] arr, int len);
   155 
   156     private static Object readFully(byte[] arr, InputStream zip) throws IOException {
   157         int offset = 0;
   158         for (;;) {
   159             int len = zip.read(arr, offset, arr.length - offset);
   160             if (len == -1) {
   161                 break;
   162             }
   163             offset += len;
   164             if (offset == arr.length) {
   165                 enlargeBytes(arr, arr.length + 4096);
   166             }
   167         }
   168         sliceArray(arr, offset);
   169         return arr;
   170     }
   171 
   172     private static long timeNow() {
   173         double time = m();
   174         if (time >= 0) {
   175             return (long)time;
   176         }
   177         return org.apidesign.bck2brwsr.emul.lang.System.currentTimeMillis();
   178     }
   179     @JavaScriptBody(args = {}, body = 
   180         "if (typeof window.performance === 'undefined') return -1;\n"
   181       + "if (typeof window.performance.now === 'undefined') return -1;\n"
   182       + "return window.performance.now();"
   183     )
   184     private static native double m();
   185     
   186     
   187 }