rt/vm/src/main/java/org/apidesign/vm4brwsr/Zips.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 20 Oct 2013 20:36:03 +0200
changeset 1375 a6c71e376889
parent 1358 65dd5a650eab
child 1387 350f8aee0f60
permissions -rw-r--r--
Can load multiple resources of the same name even in testing and development mode
     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, int skip) 
    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, skip);
    79                     skip = 0;
    80                 }
    81                 if (checkRes != null && --skip < 0) {
    82                     return checkRes;
    83                 }
    84             }
    85         }
    86         return null;
    87     }
    88     
    89     @JavaScriptBody(args = { "fn", "res", "skip" }, body = 
    90         "if (typeof fn === 'function') return fn(res, skip);\n"
    91       + "return null;"
    92     )
    93     private static native byte[] callFunction(Object fn, String res, int skip);
    94     
    95     @JavaScriptBody(args = { "msg" }, body = "if (typeof console !== 'undefined') console.log(msg.toString());")
    96     private static native void log(String msg);
    97 
    98     private byte[] findRes(String res) throws IOException {
    99         Object arr = findResImpl(res);
   100         if (arr instanceof FastJar.Entry) {
   101             long bef = timeNow();
   102             InputStream zip = fj.getInputStream((FastJar.Entry)arr);
   103             arr = readFully(new byte[512], zip);
   104             putRes(res, arr);
   105             log("Reading " + res + " took " + (timeNow() - bef) + "ms");
   106         }
   107         return (byte[]) arr;
   108     }
   109 
   110     @JavaScriptBody(args = { "res" }, body = "var r = this[res]; return r ? r : null;")
   111     private native Object findResImpl(String res);
   112 
   113     @JavaScriptBody(args = { "res", "arr" }, body = "this[res] = arr;")
   114     private native void putRes(String res, Object arr);
   115     
   116     private static Zips toZip(String path) throws IOException {
   117         URL u = new URL(path);
   118         byte[] zipData = (byte[]) u.getContent(new Class[] { byte[].class });
   119         return new Zips(path, zipData);
   120     }
   121 
   122     private static String processClassPathAttr(final byte[] man, String url, Object classpath) throws IOException {
   123         try (ParseMan is = new ParseMan(new ByteArrayInputStream(man))) {
   124             String cp = is.toString();
   125             if (cp != null) {
   126                 cp = cp.trim();
   127                 for (int p = 0; p < cp.length();) {
   128                     int n = cp.indexOf(' ', p);
   129                     if (n == -1) {
   130                         n = cp.length();
   131                     }
   132                     String el = cp.substring(p, n);
   133                     URL u = new URL(new URL(url), el);
   134                     classpath = addToArray(classpath, u.toString());
   135                     p = n + 1;
   136                 }
   137             }
   138             return is.getMainClass();
   139         }
   140     }
   141 
   142     private static Object addToArray(Object arr, String value) {
   143         final int last = length(arr);
   144         Object ret = enlargeArray(arr, last + 1);
   145         set(ret, last, value);
   146         return ret;
   147     }
   148 
   149     @JavaScriptBody(args = { "arr", "len" }, body = "while (arr.length < len) arr.push(null); return arr;")
   150     private static native Object enlargeArray(Object arr, int len);
   151     @JavaScriptBody(args = { "arr", "len" }, body = "while (arr.length < len) arr.push(0);")
   152     private static native void enlargeBytes(byte[] arr, int len);
   153 
   154     @JavaScriptBody(args = { "arr", "len" }, body = "arr.splice(len, arr.length - len);")
   155     private static native void sliceArray(byte[] arr, int len);
   156 
   157     private static Object readFully(byte[] arr, InputStream zip) throws IOException {
   158         int offset = 0;
   159         for (;;) {
   160             int len = zip.read(arr, offset, arr.length - offset);
   161             if (len == -1) {
   162                 break;
   163             }
   164             offset += len;
   165             if (offset == arr.length) {
   166                 enlargeBytes(arr, arr.length + 4096);
   167             }
   168         }
   169         sliceArray(arr, offset);
   170         return arr;
   171     }
   172 
   173     private static long timeNow() {
   174         double time = m();
   175         if (time >= 0) {
   176             return (long)time;
   177         }
   178         return org.apidesign.bck2brwsr.emul.lang.System.currentTimeMillis();
   179     }
   180     @JavaScriptBody(args = {}, body = 
   181         "if (typeof window.performance === 'undefined') return -1;\n"
   182       + "if (typeof window.performance.now === 'undefined') return -1;\n"
   183       + "return window.performance.now();"
   184     )
   185     private static native double m();
   186     
   187     
   188 }